25 JavaScript One-Liner that will help you code like a pro 🎯 !!
JavaScript is most used language in the internet. Being a developer it will be useful to know the tricks which will ease the coding. So lets check some of the one liner snippets.
We have categorized these one liners snippets based on functionality such as Array, date, Random, Validation, Web Utilities etc.
Array 🌈
1. Check if a variable is an Array
const isArray = Array.isArray(arr);
const isArray = arr instanceof Array;
2. Sum of an Array of Number
const sum = (arr) => arr.reduce((a, b) => a + b);
3. Remove Falsy value from Array
const removeFalsyValues = (arr) => arr.filter(x => x);
// or
const removeFalsyValues = (arr) => arr.filter(Boolean);
4. Average of an Array of Number
const average = (arr) => arr.reduce((a, b) => a + b) / arr.length;
5. Merge and Remove the Duplications
const merge = (arr1, arr2) => [...new Set(arr1.concat(arr2))];
// or
const merge = (arr1, arr2) => [...new Set([...arr1, ...arr2])];
6. Merge two Arrays
const merge = (arr1, arr2) => [].concat(arr1, arr2);
// or
const merge = (arr1, arr2) => [...arr1, ...arr2];
7. Shuffle an Array
const shuffle = (arr) => arr.slice().sort(() => Math.random() - 0.5);
8. Get the Last Element from an Array
const lastElement = (arr) => arr[arr.length-1];
// or
const lastElement = (arr) => arr.slice(-1)[0];
// or
const lastElement = (arr) => arr.slice().pop();
9. Find Unique Values in an Array
const findUniqueValues = (arr) => arr.filter((i) => arr.indexOf(i) === arr.lastIndexOf(i));
10. Clone an Array
const clone = (arr) => arr.slice();
// or
const clone = (arr) => [...arr];
String 🏐
11. Capitalize a String
const capitalize = (str) => str.charAt(0).toUpperCase() + str.slice(1);
12. String Reverse
const reverseString = (str) => str.split("").reverse().join("");
// or
const reverseString = (str) => [...str].reverse().join();
13. Convert a String to a Number
const toNumber = (str) => Number(str);
// or
const toNumber = (str) => +str;
14. Convert a String to a Character Array
const toCharArray = (str) => str.split('');
// or
const toCharArray = (str) => [...str];
// or
const toCharArray = (str) => Array.from(str);
// or
const toCharArray = (str) => Object.assign([], str);
15. Convert Snake case to Camel case
const snakeToCamel = (str) => str.toLowerCase().replace(/(_\w)/g, (word) => word.toUpperCase().substr(1));
Date 📅
16. Days between two dates
const daysBetweenDates = (date1, date2) => Math.ceil(Math.abs(date1 - date2) / (1000 * 60 * 60 * 24));
17. Weekday of a Date
const getWeekday = (date) => ['Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'][date.getDay()];
// or
const getWeekday = (date) => date.toLocaleString('en-US', {weekday: 'long'});
Random 🎲
18. Random Number Generator
const randomNumber = (rangeStart, rangeEnd) => new Date().getTime() % rangeEnd + rangeStart;
// or
const randomNumber = (min, max) => Math.floor(Math.random() * (max - min + 1) + min);
19. Random Hexadecimal Color Generator
const randomHexColor = () => `#${Math.random().toString(16).slice(2, 8).padEnd(6, '0')}`;
20. Random Boolean Generator
const randomBoolean = () => Math.random() >= 0.5;
Validation ✅
21. Check if an Array Is Empty
const isEmpty = (arr) => !Array.isArray(arr) || !arr.length;
22. Check if Array includes a Value
const includes = (arr, value) => arr.indexOf(value) != -1;
// or
const includes = (arr, value) => arr.includes(value);
23. Check if the date is Weekend
const isWeekend = (date) => [5, 6].indexOf(date.getDay()) !== -1;
Web Utilities 🌐
24. Copy to Clipboard
const copyToClipboard = (text) =>
navigator.clipboard?.writeText && navigator.clipboard.writeText(text);
// Testing
copyToClipboard("Hello World!");
25. Detect dark mode
const isDarkMode = () =>
window.matchMedia &&
window.matchMedia("(prefers-color-scheme: dark)").matches;
// Testing
console.log(isDarkMode());
These snippets will help you write more cleaner code and organize the functionality in less time.
Thanks for reading 😀. If you like the content, please share with more people and follow me for more such interesting topics.
https://www.linkedin.com/in/sharad-jain-304369b7/