TechWithNavi

10 Powerful JavaScript One-Liners to Streamline Your Code Effortlessly

10 Amazing JavaScript One-Liners to Simplify Your Code 🔥

JavaScript is a powerful language, and mastering it often means writing efficient, concise code. In this article, we’ll explore 10 amazing JavaScript one-liners that can simplify your code, saving you both time and effort. These one-liners are easy to understand but pack a punch in functionality, so let’s break them down in a way that’s beginner-friendly!


1. Swap Two Variables Without a Temporary Variable

[a, b] = [b, a];

Explanation:

In JavaScript, you often swap two variables by using a temporary third variable:

let temp = a;
a = b;
b = temp;

But with array destructuring, you can do it in a single line. [a, b] = [b, a]; swaps a and b without needing that temporary variable. It works by creating an array on the right-hand side [b, a] and immediately destructuring it into a and b. This is cleaner and more elegant!


2. Check if a Number is Even

const isEven = n => n % 2 === 0;

Explanation:

This one-liner creates a function isEven, which checks if a number n is even. It uses the modulus operator (%), which gives the remainder when n is divided by 2. If the remainder is 0 (n % 2 === 0), the number is even; otherwise, it’s odd.

For example:

console.log(isEven(4)); // true
console.log(isEven(7)); // false

3. Flatten an Array

const flattened = arr => arr.flat(Infinity);

Explanation:

Arrays can sometimes be nested within other arrays, making them “multi-dimensional.” Flattening an array means converting it into a single array with all its values at the same level. The flat() method takes an array and “flattens” it. By passing Infinity to flat(), you ensure that no matter how deep the array is nested, it will flatten everything.

Example:

const arr = [1, [2, [3, [4]]]];
console.log(flattened(arr)); // [1, 2, 3, 4]

4. Generate a Random Number Between Two Values

const randomBetween = (min, max) => Math.random() * (max - min) + min;

Explanation:

Math.random() generates a random number between 0 and 1. To scale this to a desired range (between min and max), you multiply the result by (max - min) and add min to shift it into the desired range.

Example:

console.log(randomBetween(5, 10)); // Outputs a random number between 5 and 10

5. Capitalize the First Letter of a String

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

Explanation:

Here, we’re turning the first character of a string into uppercase. The method charAt(0) gets the first character, toUpperCase() converts it to uppercase, and slice(1) gets the rest of the string (from index 1 to the end). We then concatenate these two parts.

Example:

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

6. Remove Duplicates from an Array

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

Explanation:

The Set object automatically removes duplicates from an array because sets only store unique values. By using the spread operator (...), we convert the set back into an array, but now with only unique values.

Example:

const arr = [1, 2, 2, 3, 3, 4];
console.log(unique(arr)); // [1, 2, 3, 4]

7. Get the Last Item in an Array

const lastItem = arr => arr[arr.length - 1];

Explanation:

To get the last item in an array, you can access it by its index. The last index of an array is arr.length - 1 because array indices start at 0. This one-liner gets that last element efficiently.

Example:

const numbers = [10, 20, 30, 40];
console.log(lastItem(numbers)); // 40

8. Check if a String is a Palindrome

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

Explanation:

A palindrome is a string that reads the same forwards and backwards. This one-liner checks if a string is a palindrome by:

  1. Splitting the string into an array of characters (split('')),
  2. Reversing the array (reverse()),
  3. Joining the array back into a string (join('')),
  4. Comparing the reversed string to the original.

Example:

console.log(isPalindrome('racecar')); // true
console.log(isPalindrome('hello'));   // false

9. Sum an Array of Numbers

const sum = arr => arr.reduce((acc, num) => acc + num, 0);

Explanation:

The reduce() method processes each array element and reduces it to a single value. Here, we’re summing up all the numbers in the array. The acc (accumulator) keeps a running total, and num is the current number being added.

Example:

const numbers = [1, 2, 3, 4];
console.log(sum(numbers)); // 10

10. Generate a Range of Numbers

const range = (start, end) => Array.from({ length: end - start + 1 }, (_, i) => start + i);

Explanation:

This one-liner creates an array containing a range of numbers between start and end. Array.from creates an array of a specific length (end - start + 1), and the second argument (a map function) generates numbers from start to end.

Example:

console.log(range(5, 10)); // [5, 6, 7, 8, 9, 10]

Conclusion

By mastering these JavaScript one-liners, you can write more concise, elegant, and efficient code. While these snippets are compact, they’re also powerful and can be integrated into more complex projects. Keep practicing, and soon these tricks will become second nature in your coding workflow!

Let's connect - webatapp8@gmail.com