
Back to all articles
JS One-liners That Save Time
A collection of JavaScript one-liners that save time.
Simen Daehlin
2 min read
Article Stats
Reading Time2 min read
Word Count233 words
Published On
AuthorSimen Daehlin
Table of Contents
TABLE OF CONTENTS
Table of Contents
TABLE OF CONTENTS

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.
Javascript
const removeDuplicates = (arr) => [...new Set(arr)]; console.log(removeDuplicates(["🙏","🙏","😇","😇","🥷"])); // result: ['🙏', '😇', '🥷']
Check if a number is even or odd
Always wanted to find out if a number is odd or even?
Javascript
const isEven = num => num % 2 === 0; console.log(isEven(2)); // result: true
Go To top
No need to target an anchor tag we can just scroll to the top.
Javascript
const goToTop = () => window.scrollTo(0, 0); goToTop();
Shuffle an Array
There are many good ways to do this with algorithms though this is just using sort
and Math.random
Javascript
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.
Javascript
const isDarkMode = window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches console.log(isDarkMode) // result: True or False
Capitalise a String
Javascript
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 👇