DEV Community

SOVANNARO
SOVANNARO

Posted on

10 JavaScript One-Liners That Make Developer Life Easier

JavaScript is a versatile language with a lot of powerful features. Sometimes, the simplest solutions can be the most effective. Here are 10 JavaScript one-liners that can make your coding life easier and more efficient.

1. Swapping Two Variables

Swapping values between two variables is a common task. Instead of using a temporary variable, you can do it in one line with destructuring assignment.

let a = 5, b = 10;
[a, b] = [b, a];
console.log(a); // 10
console.log(b); // 5
Enter fullscreen mode Exit fullscreen mode

2. Checking if a Number is Even or Odd

You can check if a number is even or odd using the modulus operator.

const isEven = num => num % 2 === 0;
console.log(isEven(4)); // true
console.log(isEven(7)); // false
Enter fullscreen mode Exit fullscreen mode

3. Generating a Random Number in a Range

Generating a random number within a specific range can be done in one line.

const randomInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
console.log(randomInRange(1, 10)); // e.g., 5
Enter fullscreen mode Exit fullscreen mode

4. Removing Duplicates from an Array

Use the Set object to remove duplicates from an array.

const removeDuplicates = arr => [...new Set(arr)];
console.log(removeDuplicates([1, 2, 2, 3, 4, 4])); // [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

5. Flattening an Array

Flatten a nested array using the flat method.

const flattenArray = arr => arr.flat(Infinity);
console.log(flattenArray([1, [2, [3, [4]]]])); // [1, 2, 3, 4]
Enter fullscreen mode Exit fullscreen mode

6. Checking if an Element Exists in an Array

Use the includes method to check if an element exists in an array.

const existsInArray = (arr, element) => arr.includes(element);
console.log(existsInArray([1, 2, 3], 2)); // true
console.log(existsInArray([1, 2, 3], 4)); // false
Enter fullscreen mode Exit fullscreen mode

7. Converting an Array to a String

Convert an array to a string using the join method.

const arrayToString = arr => arr.join('');
console.log(arrayToString(['H', 'e', 'l', 'l', 'o'])); // "Hello"
Enter fullscreen mode Exit fullscreen mode

8. Reversing a String

Reverse a string using the split, reverse, and join methods.

const reverseString = str => str.split('').reverse().join('');
console.log(reverseString('hello')); // "olleh"
Enter fullscreen mode Exit fullscreen mode

9. Getting the Current Date in YYYY-MM-DD Format

Format the current date as YYYY-MM-DD.

const getCurrentDate = () => new Date().toISOString().split('T')[0];
console.log(getCurrentDate()); // e.g., "2023-10-01"
Enter fullscreen mode Exit fullscreen mode

10. Capitalizing the First Letter of a String

Capitalize the first letter of a string.

const capitalizeFirstLetter = str => str.charAt(0).toUpperCase() + str.slice(1);
console.log(capitalizeFirstLetter('hello')); // "Hello"
Enter fullscreen mode Exit fullscreen mode

Conclusion

These one-liners can save you time and make your code more concise. Whether you're swapping variables, checking for even numbers, or formatting dates, these snippets can be a handy addition to your JavaScript toolkit. Happy coding!


Top comments (1)

Collapse
 
webjose profile image
José Pablo Ramírez Vargas • Edited

One more of those.

Several "utilities" are effectively renames of something else. flattenArray -> array.flat(). Same thing, zero gain, and the cherry on top: You use more RAM.

Then the eternal problem of people thinking things are magical: str.spit('').reverse().join(''). This creates an array (wasted RAM), then runs a loop, then runs another loop. This is a good candidate for the least performer of the year.

function reverse(str: string) {
  let result = '';
  for (let i = str.length - 1; i >= 0; --i) {
    result += str[i];
  }
  return result;
}
Enter fullscreen mode Exit fullscreen mode

Now that's a much better "utility".