One-Liners in JavaScript

Home » Programming » One-Liners in JavaScript

One-Liners in JavaScript

Javascript

 

JavaScript can do a lot of things. Here is a list of one-liners you should know to become a JavaScript pro.

 

1. Swap variables

let a = 10;
let b = 20;
[a, b] = [b,a];

console.log(a,b); // 20 10

 

2. Unique Elements

Javascript has its own implementation of Hashmap known as Set.

const arr = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4];
const uniqueValuesArr = (arr) => [...new Set(arr)];

console.log(uniqueValuesArr(arr)); // [1,2,3,4]

 

3. Detect Dark Mode

Now a days it is common to add a option to switch between light and dark theme on website. Here media queries can be used to detect which theme is currently applied.

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

console.log(isDarkMode()); // false (check in websites that support both light, dark theme)

The support of matchMedia is 97.79%.

 

4. Remove falsy values from array

Pass Boolean as  parameter and you will be able to filter out all falsy values in the array.

const removeFalsyValues = (arr) => arr.filter(Boolean)
const arr = [0, 'Ani', '', NaN, true, 27, undefined, 'developer', false];

console.log(removeFalsyValues(arr)); //['Ani', true, 27, 'developer']

 

5. Get average value of arguments

We can use the reduce method to get the average value of the arguments that we provide in this function.

const average = (...args) => args.reduce((a, b) => a + b) / args.length;

console.log(average(1, 2, 3, 4)); // 2.5

 

6. Check if the provided day is a weekday

const isWeekday = (date) => date.getDay() % 6 !== 0;

console.log(isWeekday(new Date(2022, 11, 10))); // false (Saturday)
console.log(isWeekday(new Date(2022, 11, 9)));  // true (Friday)

 

7. Scroll To Top

This is very common question of beginners. The easiest way to scroll elements is to use the scrollIntoView method. To have a smooth scrolling animation, add behavior: “smooth” parameter.

const scrollToTop = (element) => element.scrollIntoView({ behavior: "smooth"});

 

8. Reverse a string

This is a simple one using split(), reverse() and join() methods.

const reverseString = (str) => str.split('').reverse().join('');

console.log(reverseString('hello world')); // dlrow olleh

 

9. Copy to clipboard

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

console.log(copyToClipboard("Hello World"));

 

10. Capitalise a string

We can use the following code to capitalise a string, as Javascript doesn’t have an inbuilt capitalise function.

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

console.log(capitalize("hello world")); //Hello world

 

I hope these one-liners will help you make more effective use of JavaScript in your future projects.