01 - Remove Duplicates from an Array
const uniqueArr = arr => [...new Set(arr)];
console.log(uniqueArr([1, 2, 3, 4, 5, 5, 5]));
// [1, 2, 3, 4, 5]
02 - Sum of Array Elements
const nums = [1, 2, 3, 4, 5];
const sum = nums.reduce((acc, num) => acc + num);
console.log(sum);
// 15
03 - Check if a Number is Odd or Even
const isEven = num => num % 2 === 0;
console.log(isEven(5));
// false
04 - Capitalize Every Word in a String
const capitalizeWords = str =>
str.split(' ')
.map(word => word.charAt(0).toUpperCase() + word.slice(1))
.join(' ');
console.log(capitalizeWords('hello world'));
// 'Hello World'
05 - Reverse a String (By letters & words)
let str = 'Hello World!';
console.log(str.split('').reverse().join(''));
console.log(str.split(' ').reverse().join(' '));
// '!dlroW olleH'
// 'World! Hello'
06 - Truncate a String to a Specific Length
const truncate = (str, len) => str.slice(0, len) + '...';
console.log(truncate("Lorem ipsum is simply dummy text of the printing and typesetting industry.", 15));
// 'Lorem ipsum is...'
07 - Short-Circuit Evaluation
const fullName = fname || 'John Doe';
console.log(fullName);
// 'John Doe'
08 - Remove a Specific Value from an Array
const toRemove = 5;
const newArr = nums.filter(val => val !== toRemove);
console.log(newArr);
// [1, 2, 3, 4]
09 - Swap Two Variables
[a, b] = [b, a];
10 - Toggle a Boolean Value
const toggle = bool => !bool;
11 - Generate a Random String
const randomString = () => Math.random().toString(36).slice(2);
console.log(randomString());
// 'eqsdasfefsa' // Example output
12 - Detect Dark Mode
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').match;
13 - Scroll to the Top of the Page
const scrollTop = () => window.scrollTo(0, 0);
14 - Replace switch with Object Literals
// Traditional way ๐
const getAnimalName = (animalType) => {
switch (animalType) {
case 'lion':
return '๐ฆ';
case 'elephant':
return '๐';
case 'tiger':
return '๐
';
default:
return 'Unknown';
}
};
// Using object literals ๐
const animalNames = {
lion: '๐ฆ',
elephant: '๐',
tiger: '๐
',
};
const getAnimalName = animalType => animalNames[animalType] || 'Unknown';
console.log(getAnimalName('lion'));
// '๐ฆ'
These one-liners offer quick solutions to common JavaScript tasks, helping you write cleaner, more efficient code. Give them a try!
Top comments (2)
The 10th oneliner does not toggle a boolean, it merely inverts it (and you might not want a whole function to do that).
It actually does.
Inverting a boolean value and toggling a boolean value is one and the same