Atul Kumar
AKumar

Follow

AKumar

Follow
Killer JavaScript One Liners

Killer JavaScript One Liners

JavaScript One Liners to Solve Common Problems

Atul Kumar's photo
Atul Kumar
ยทSep 18, 2022ยท

6 min read

Table of contents

Hello Devs ๐Ÿ‘‹

This is Atul here. Many times, in our development workflow, we come across complex problems which require only one line of code to be solved.

I've curated 39 code snippets so that you can use them in future codebases ๐Ÿ‘‡

1. Convert a color from RGB to Hex

const rgbToHex = (r, g, b) => '#' + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

rgbToHex(0, 0, 0);    // #000000

You can learn about left shift on MDN

2. Copy to Clipboard

const copyToClipboard = async text => {
    await navigator.clipboard.writeText(text);
}

copyToClipboard("@kumartul");

// Hit Ctrl/Cmd + V in any text box, @kumartul will be printed

You can learn about Clipboard API on MDN

3. Find which Day of the Year it is

For example, January 1, 2022, will be the first day of the year 2022, January 2, 2022, will be the second day of the year 2022, and so on...

const dayOfYear = date => Math.floor((date - new Date(date.getFullYear(), 0, 0)) / 1000 / 60 / 60 / 24);

dayOfYear(new Date());

4. Capitalise a String

const capitalise = str => str[0].toUpperCase() + str.slice(1);

capitalise('follow @kumartul');    // Follow @kumartul

5. Find the number of days between two dates

const dateDiff = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000);

6. Generate a random Hexadecimal Color

const randomHex = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, '0')}`;

7. Remove Duplicate Values from an Array

const removeDuplicate = arr => [...new Set(arr)];

removeDuplicate([1, 2, 3, 1, 3, 1, 3, 2, 4]);    // [1, 2, 3, 4]

8. Find the arithmetic mean (average) of all the numbers passed in as arguments

const mean = (...nums) => nums.reduce((a, b) => a + b) / nums.length;

mean(1, 3, 4, 2);    // 2.5

9. Scroll to the top of the Window

const scrollToTop = window.scrollTo(0, 0);

10. Reverse a String

const revStr = str => str.split('').reverse().join('');

revStr('@kumartul');    // lutramuk@

11. Get Selected Text in the Window

 const getSelectedText = () => window.getSelection.toString();

12. Shuffle an Array

const shuffle = arr => arr.sort(() => 0.5 - Math.random());

shuffle([1, 2, 3]);    // [2, 3, 1]

13. Check if the user is in dark mode

const isDarkMode = () => window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches;

isDarkMode();

14. Swap the values of two variables with destructuring

let a = 0;
let b = 1;

[a, b] = [b, a];

console.log(a);    // 1
console.log(b);    // 0

15. Remove Falsy Values from an Array

const removeFalsyValues = arr => arr.filter(Boolean);

Falsy Values: undefined, null, NaN, 0, '', "", false

16. Merge Multiple Arrays

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];

const mergedArr = [...arr1, ...arr2];

console.log(mergedArr);    // [1, 2, 3, 4, 5, 6]

17. Clone an Array

 const cloneArr = arr => [...arr];

const arr = [1, 2, 3];
const clonedArr = cloneArr(arr);

console.log(clonedArr);    // [1, 2, 3]

We are not assigning the original array to the cloned array because Array is a reference data type and if we make changes in either of the arrays, then changes will be reflected in both the arrays and that's not what we want

18. Generate a Random Integer within the given range

const random = (min, max) => Math.floor(Math.random() * (max - min)) + min;

random(1, 10);    // 7

19. Round off a number to the given number of places

const PI = 3.141592653589793238462643383279;

console.log(PI.toFixed(2));    // 3.14

20. Convert snake_case to camelCase

const convertSnakeToCamel = str => str.toLowerCase().replace(/(_\w)/g, w => w.toUpperCase().substr(1));

convertSnakeToCamel('random_num');    // randomNum

21. Detect if the user's browser is an Apple Browser

const isAppleBrowser = () => /Mac|iPod|iPhone|iPad/.test(navigator.platform);

isAppleBrowser();

22. Filter Unique Values in an Array

const findUniqueValuesInArr = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));

console.log(findUniqueValuesInArr([1, 2, 3, 2, 1, 5]));    // [3, 5]

23. Check if your code is running in a Browser

const isRunningInBrowser = typeof window === 'object' && typeof document === 'object';

console.log(isRunningInBrowser);

24. Generate a UUID (without using uuidv4 npm package)

const generateRandomUUID = a => (a ? (a ^ ((Math.random() * 16) >> (a / 4))).toString(16) : ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, generateRandomUUID));

generateRandomUUID();

25. Generate a random unique ID

const randomID = Math.random().toString(36).substring(2);

randomID();

26. Check if the element is focussed/active in the document

const hasFocus = elem => elem === document.activeElement;

console.log(hasFocus(document.getElementById('userInput')));

27. Go to previous page

history.back();

28. Count the number of properties in an array of objects

const count = (arr, prop) => arr.reduce((prev, curr) => ((prev[curr[prop]] == ++prev[curr[prop]] || 1), prev), {});

const persons = [
    {
        name: 'A',
        age: 10
    },
    {
        name: 'B',
        age: 13
    },
    {
        name: 'C',
        age: 10
    }
];

count(persons, 'age');    // { 10: 2, 13: 1 }

29. Check if all the objects are equal

const isEqual = (...objects) => objects.every(obj => JSON.stringify(obj) === JSON.stringify(objects[0]));

isEqual({ a: 1 }, { a: 1 }, { c : 3});    // false

30. Invert Keys and Properties of an Object

const invert = obj => Object.fromEntries(Object.entries(obj).map(([k, v]) => [v, k]));

invert({ a: 1, b: 2 });

31. Check if the argument is a promise

const isPromise = obj => !!obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function';

const promise = new Promise((resolve, reject) => resolve());

isPromise(promise);

32. Empty an Array

const arr = [1, 2, 3];
arr.length = 0;

console.log(arr);    // []

33. Check if the device supports touch events

const supportTouchEvents = () => window && 'ontouchstart' in window;

supportTouchEvents();

34. Check the preferred language of the user

const detectLanguage = (lang = 'en-US') => navigator.language || (Array.isArray(navigator.languages)) && navigator.languages[0]) || defaultLang;

35. Check if the Date is valid

const isDateValid = (...val) => !Number.isNaN(new Date(...val).valueOf());

36. Check if the URL is absolute

const isAbsoluteURL = str => /^[a-z][a-z0-9+.-]*:/.test(str);

37. Smooth-scroll Element into View

const smoothScroll = element => document.querySelector(element).scrollIntoView({ behavior: 'smooth' });

38. Toggle Full-Screen Mode

const fullscreen = (mode = true, elem = 'body') => mode ? document.querySelector(elem).requestFullscreen() : document.exitFullscreen();

39. Detect if Caps Lock is On

const msgInput = document.getElementById('msgInput');

msgInput.addEventListener('keyup', event => {
    console.log(event.getModifierState('CapsLock');
});

Wrapping Up ๐Ÿ‘‹

I hope you enjoyed the article and will make the best use of these code snippets in your upcoming projects.

Comments and reactions are highly appreciated! ๐Ÿ™Œ Have an amazing day!

ย 
Share this