6 JS one-liners that save time.

6 JS one-liners that save time.


2 min read

Here are 6 Js one-liners that just saves me time when I write code.

Remove Duplicated from Array

You can easily remove duplicates with Set in JavaScript. It's a lifesaver.

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

// result: ['๐Ÿ™', '๐Ÿ˜‡', '๐Ÿฅท']

Check if a number is even or odd

Always wanted to find out if a number is odd or even?

const isEven = num => num % 2 === 0;

// result: true

Go To top

No need to target an anchor tag we can just scroll to the top.

const goToTop = () => window.scrollTo(0, 0);


Shuffle an Array

There are many good ways to do this with algorithms though this is just using sort and Math.random

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

console.log(shuffleArray([1, 2, 3, 4]));
// result: [ 1, 4, 3, 2 ]

Detect Darkmode on the user system

Great if you want to toggle styles but find out what they are using first.

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

console.log(isDarkMode) // result: True or False

Capitalise a String

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1)

capitalize("follow for more")
// result: Follow for more

Do you have any good one-liners? If so please do share them in the comments below ๐Ÿ‘‡