10 Useful JavaScript One-Liners to Improve Your Efficiency

This article compiles very useful one-liners that are commonly needed in development, which can help you improve your work efficiency.

JavaScript is known for being easy to learn and incredibly flexible, with a wide variety of ways to implement code; sometimes, if you can solve something in one line, you don't need two.

This article compiles very useful one-liners that are commonly needed in development, which can help you improve your work efficiency.

Array Deduplication

To remove all duplicate values from an array, there are many ways to do it, but here's the simplest way, all in one line:

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

console.log(uniqueArr(["frontend","js","html","js","css","html"]));
// ['frontend', 'js', 'html', 'css']

The uniqueArr function converts the data to a Set and then destructures it back into an array.

Get Parameters from URL and Convert to Object

Web page paths often look like this: www.baidu.com?search=js&xxx=kkk. We often need to extract parameters, and you can do this with one line of code without needing to introduce the qs package.

const getParameters = URL => JSON.parse(`{"${decodeURI(URL.split("?")[1]).replace(/"/g, '\\"').replace(/&/g, '","').replace(/=/g, '":"')}"}`)

getParameters("https://www.google.com.hk/search?q=js+md&newwindow=1"); 
// {q: 'js+md', newwindow: '1'}

Check if an Object is Empty

Checking if an object is empty is not as simple as it seems; even if an object is empty, checking if it equals {} will always return false.

Fortunately, the following one-liner is exactly what we want.

const isEmpty = obj => Reflect.ownKeys(obj).length === 0 && obj.constructor === Object;
isEmpty({}) // true
isEmpty({a:"not empty"}) //false

Reverse a String

Reversing a string can be easily achieved using split combined with reverse and join.

const reverse = str => str.split(').reverse().join(');
reverse('this is reverse');
// esrever si siht

Generate Random Hexadecimal

Generating random numbers is easy, but how about generating a random hexadecimal, such as a color value?

const randomHexColor = () => `#${Math.floor(Math.random() * 0xffffff).toString(16).padEnd(6, "0")}`
console.log(randomHexColor());
// #a2ce5b

Check if the Current Tab is Active

Browsers use tabbed browsing, and any web page could be in the background, which means it's not being viewed by the user. Do you know how to quickly detect whether your web page is hidden or visible?

const isTabActive = () => !document.hidden; 

isTabActive()
// true|false

Check if an Element is in Focus

The activeElement property returns the element in the document that currently has focus.

const elementIsInFocus = (el) => (el === document.activeElement);

elementIsInFocus(anyElement)
// true if the element is in focus, false otherwise

Check Device Type

Using navigator.userAgent to determine whether it's a mobile device or a computer:

const judgeDeviceType =
      () => /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|OperaMini/i.test(navigator.userAgent) ? 'Mobile' : 'PC';

judgeDeviceType()  // PC | Mobile

Copy Text to Clipboard

The Clipboard API is asynchronous, returning a Promise object, which doesn't cause the page to hang. Moreover, it can put any content (like images) into the clipboard.

const copyText = async (text) => await navigator.clipboard.writeText(text)
copyText('One-liner JavaScript world')

Get Selected Text

Use the built-in getSelection to get the text selected by the user:

const getSelectedText = () => window.getSelection().toString();

getSelectedText();
// Returns the selected content

Check if a Day is a Working Day

When we write our own calendar components, we often need to determine if a certain date is a working day; Monday to Friday are working days:

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

isWeekday(new Date("2022-03-11"))
// true

Convert Fahrenheit to Celsius

Dealing with temperatures can be confusing. These two functions help you convert Fahrenheit to Celsius and vice versa.

  • Convert Fahrenheit to Celsius
const fahrenheitToCelsius = (fahrenheit) => (fahrenheit - 32) * 5/9;

fahrenheitToCelsius(50);
// 10
  • Convert Celsius to Fahrenheit
const celsiusToFahrenheit = (celsius) => celsius * 9/5 + 32;

celsiusToFahrenheit(100)
// 212

Calculate the Number of Days Between Two Dates

In everyday development, we often need to display the remaining days, so we need to calculate the number of days between two dates:

const dayDiff = (date1, date2) => Math.ceil(Math.abs(date1.getTime() - date2.getTime()) / 86400000);

dayDiff(new Date("2021-10-21"), new Date("2022-02-12"))
// Result: 114

Convert RGB to Hexadecimal

const rgbToHex = (r, g, b) =>   "#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);

rgbToHex(255, 255, 255); 
//  #ffffff

Calculate the Average of an Array

There are many ways to calculate the average, and the logic is always the same, but the implementation varies. Here's a simple one-liner:

const average = (arr) => arr.reduce((a, b) => a + b) / arr.length;
average([1,9,18,36]) //16

What are your commonly used one-liners?

Continue Learning

Discover more articles on similar topics