DEV Community

Cover image for 14 JavaScript One-Liners to Boost Your Productivity πŸš€
Durvesh Danve
Durvesh Danve

Posted on

12 1 1 1 1

14 JavaScript One-Liners to Boost Your Productivity πŸš€

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]
Enter fullscreen mode Exit fullscreen mode

02 - Sum of Array Elements

const nums = [1, 2, 3, 4, 5];
const sum = nums.reduce((acc, num) => acc + num);
console.log(sum);

// 15
Enter fullscreen mode Exit fullscreen mode

03 - Check if a Number is Odd or Even

const isEven = num => num % 2 === 0;
console.log(isEven(5));

// false
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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'
Enter fullscreen mode Exit fullscreen mode

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...'
Enter fullscreen mode Exit fullscreen mode

07 - Short-Circuit Evaluation

const fullName = fname || 'John Doe';
console.log(fullName);

// 'John Doe'
Enter fullscreen mode Exit fullscreen mode

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]
Enter fullscreen mode Exit fullscreen mode

09 - Swap Two Variables

[a, b] = [b, a];
Enter fullscreen mode Exit fullscreen mode

10 - Toggle a Boolean Value

const toggle = bool => !bool;
Enter fullscreen mode Exit fullscreen mode

11 - Generate a Random String

const randomString = () => Math.random().toString(36).slice(2);
console.log(randomString());

// 'eqsdasfefsa'  // Example output
Enter fullscreen mode Exit fullscreen mode

12 - Detect Dark Mode

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

Enter fullscreen mode Exit fullscreen mode

13 - Scroll to the Top of the Page

const scrollTop = () => window.scrollTo(0, 0);
Enter fullscreen mode Exit fullscreen mode

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'));

// '🦁'
Enter fullscreen mode Exit fullscreen mode

These one-liners offer quick solutions to common JavaScript tasks, helping you write cleaner, more efficient code. Give them a try!

Sentry image

See why 4M developers consider Sentry, β€œnot bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (2)

Collapse
 
fsabre profile image
FSabre β€’ β€’ Edited

The 10th oneliner does not toggle a boolean, it merely inverts it (and you might not want a whole function to do that).

Collapse
 
durvesh_danve profile image
Durvesh Danve β€’

It actually does.
Inverting a boolean value and toggling a boolean value is one and the same

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free β†’

The only thing worse than downtime? No Answers.

If you’re sometimes frustrated with opaque infrastructure, sluggish support, and mysterious outages, we prepared a webinar just for you

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❀️