10+ Killer JavaScript One Liners 🔥

Lokesh Prajapati
2 min readMay 13, 2023

--

👋 Want to maximize your JavaScript skills?

Every JS developer should use javascript one liners to improve productivity and skills, so today we discuss some of one liners which we can use in our daily development life.

1. Sort an Array

Sort an array is super easy with sort method.

const number = [2,6,3,7,8,4,0];number.sort(); 
// expected output: [0,2,3,4,6,7,8]

2. Check value in an Array

Many times we need to check value is exist in array or not, with help of includes method.

const array1 = [1, 2, 3];console.log(array1.includes(2));
// expected output: true

3. Filter an Array

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]

4. Find element from an Array

If you need only one element but you getting many number of element in array, don’t worry JavaScript have find method.

const array1 = [5, 12, 8, 130, 44];const found = array1.find(element => element > 10);console.log(found);
// expected output: 12

5. Find index of any element in an Array

For find index of an element in array, you can simply use indexOf method.

const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];console.log(beasts.indexOf('bison'));
// expected output: 1

6. Convert an array to string

const elements = ['Fire', 'Air', 'Water'];console.log(elements.join(", "));
// expected output: "Fire, Air, Water"

7. Check number is even or odd

It’s very easy to find out given number is even or odd

const isEven = num => num % 2 === 0;
or
const isEven = num => !(n & 1);

8. Remove all duplicate values in an array

A very easy way to remove all duplicate values in an array

const setArray = arr => [...new Set(arr)];const arr = [1,2,3,4,5,1,3,4,5,2,6];
setArray(arr);
// expected output: [1,2,3,4,5,6]

9. Different ways of merging multiple arrays

// merge but don't remove duplications
const merge = (a, b) => a.concat(b);
or
const merge = (a, b) => [...a, ...b];// merge with remove duplications
const merge = (a, b) => [...new Set(a.concat(b))];
or
const merge = (a, b) => [...new Set([...a, ...b])];

10. Scroll to top of the page

There is many way to scroll page to top.

const goToTop = () => window.scrollTo(0,0, "smooth");
or
const scrollToTop = (element) => element.scrollIntoView({behavior: "smooth", block: "start"});// scroll to bottom of the page
const scrollToBottom = () => window.scrollTo(0, document.body.scrollHeight);

11. Copy to Clipboard

In web apps, copy to clipboard is rapidly rising in popularity due to its convenience for the user.

const copyToClipboard = text => (navigator.clipboard?.writeText ?? Promise.reject)(text);

--

--