5 JavaScript One Liners that Every Developer Should Use

Pheonix
3 min readJun 22, 2023
Computer screen in a table
Photo by Christopher Gower on Unsplash

JavaScript is a versatile programming language that allows developers to write powerful and concise code.

One-liners are short code snippets that can accomplish complex tasks in a single line. This article will explore 5 JavaScript one-liners that every developer should know. These techniques can help enhance code readability, reduce the number of lines of code, and improve overall efficiency.

1. Get a Random Element

const getRandomItem = (items) =>  items[Math.floor(Math.random() * items.length)];
const items = ["Nicely done!", "Good job!", "Good work!", "Correct!"];
getRandomItem(items); // "Good work!"

Getting a random element and array is nice when you want to make things unique for your user.

For example, you might want to show your users a congratulations message based on some action. But you probably don’t want to show them the same one every time, because that would get repetitive and boring.

getRandomItem uses the Math.random() function, which returns a decimal between 0 and 1. This is multiplied by the length of the array to select a random index, which can be used to select a random element.

2. Remove Duplicate Elements

const removeDuplicates = (arr) => [...new Set(arr)];
const friendList = ["Rahul", "Priya", "Rahul", "Pranab"];
removeDuplicates(friendList); // ['Rahul', 'Priya', 'Pranab']

Removing duplicate values in an array is an essential task in JavaScript.

For example, you might be adding one user to another user’s friends list, but you don’t want that user to be added or displayed twice.

This removeDuplicates function leverages the Set constructor in JavaScript, which removes any duplicate (primitive) values by default. After that, we use the spread operator ... to spread its values into a new array.

3. Check if Arrays/Objects are Equal

const isEqual = (a, b) => JSON.stringify(a) === JSON.stringify(b);
isEqual([1, '2'], [1, 2]); // false
isEqual([1, 2], [1, 2]); // true

It’s easy to check for equality with JavaScript primitives, like numbers and strings.

Checking for equality between arrays and objects is a bit harder, however. Fortunately, there’s a neat trick you can use JSON.stringify to convert arrays or objects into a JSON string. If all the elements match, isEqual will return a value of true.

This is very handy when you expect multiple inputs from a user, for example, if they’re answering a question and you want to compare it to the correct solution.

4. Wait for a Certain Amount of Time

const wait = async (milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds));
wait(2000).then(() => goToSignupPage());

In your application, you might want to wait for a certain period of time. For example, if you want to delay an animation or are waiting for an important operation to finish.

You can provide the wait function a certain amount of time to wait in milliseconds. Because it uses a promise, you can use the then callback or the await keyword to make sure it has finished.

5. Insert an Element at a Certain Position

const insert = (arr, index, newItem) => [...arr.slice(0, index), newItem, ...arr.slice(index)];
const items = [1, 2, 4, 5];

// insert the number 3 at index 2:

insert(items, 2, 3); // [1, 2, 3, 4, 5]

If we want to put an element in a precise location in an array, we can use this special insert function.

To use it, we just need to pass to insert the array we want to transform, the index where we want the element to insert, and the element to insert.

This is a great function to use instead .splice() because it does not mutate the original array. It creates a new array with the help of the slice method, by slicing the array into two parts around the specified index and then creates a new one.

By utilizing these 5 JavaScript one-liners, developers can write more efficient and expressive code.

It’s important to note that while one-liners can improve code readability and conciseness, they should be used judiciously to maintain code clarity and avoid sacrificing readability for the sake of brevity.

If this article was helpful, Please tweet it and Clap ✌️

--

--