01 – Remove Duplicates from an Array
console.log(uniqueArr([1, 2, 3, 4, 5, 5, 5]));
// [1, 2, 3, 4, 5]
02 – Sum of Array Elements
const sum = nums.reduce((acc, num) => acc + num);
console.log(sum);
// 15
03 – Check if a Number is Odd or Even
console.log(isEven(5));
// false
04 – Capitalize Every Word in a String
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)
console.log(str.split(”).reverse().join(”));
console.log(str.split(‘ ‘).reverse().join(‘ ‘));
// ‘!dlroW olleH’
// ‘World! Hello’
06 – Truncate a String to a Specific Length
console.log(truncate(“Lorem ipsum is simply dummy text of the printing and typesetting industry.“, 15));
// ‘Lorem ipsum is…’
07 – Short-Circuit Evaluation
console.log(fullName);
// ‘John Doe’
08 – Remove a Specific Value from an Array
const newArr = nums.filter(val => val !== toRemove);
console.log(newArr);
// [1, 2, 3, 4]
09 – Swap Two Variables
10 – Toggle a Boolean Value
11 – Generate a Random String
console.log(randomString());
// ‘eqsdasfefsa’ // Example output
12 – Detect Dark Mode
13 – Scroll to the Top of the Page
14 – Replace switch with Object Literals
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!