DEV Community

Cover image for Stop Writing Long JS Code — Use These 10 Time-Saving One-Liners Instead
Siddhesh Mithbavkar
Siddhesh Mithbavkar

Posted on

Stop Writing Long JS Code — Use These 10 Time-Saving One-Liners Instead

As developers, we often find ourselves writing repetitive snippets — loops, condition checks, or small transformations — over and over again.

But what if you could replace those 5–10 lines of code with just one smart JavaScript line?

In this post, we’ll explore 10 powerful JS one-liners that can save you hours while keeping your code clean, elegant, and efficient.

1. Swap Two Variables Without a Temporary Variable

[a, b] = [b, a];
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:
No need for an extra variable to swap values. This uses array destructuring, a neat ES6 feature.

Example:

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

2. Convert a String to a Number Instantly

const num = +str;
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:
A fast, clean alternative to parseInt() or Number(). Works great when you’re sure the value is numeric.

Example:

const price = "49";
console.log(+price + 1); // 50
Enter fullscreen mode Exit fullscreen mode

3. Get the Current Timestamp

const now = Date.now();
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:
Instead of creating a full Date object, this gives you the milliseconds since Unix epoch in one line.

Example:

console.log(Date.now()); // 1730830420000
Enter fullscreen mode Exit fullscreen mode

4. Remove Duplicates from an Array

const unique = [...new Set(arr)];
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:
Simplifies what used to require loops or filter(). The Set automatically keeps only unique values.

Example:

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

5. Flatten a Nested Array

const flat = arr.flat(Infinity);
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:
Instead of recursive loops, this flattens deeply nested arrays in one go.

Example:

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

6. Generate a Random Integer in a Range

const rand = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:
Perfect for games, mock data, or random testing. Clean and reusable.

Example:

console.log(rand(10, 20)); // e.g., 17
Enter fullscreen mode Exit fullscreen mode

7. Check for Palindrome in One Line

const isPalindrome = str => str === str.split('').reverse().join('');
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:
Quickly checks if a string reads the same backward. Ideal for interview prep or input validation.

Example:

console.log(isPalindrome("madam")); // true
Enter fullscreen mode Exit fullscreen mode

8. Count Occurrences in an Array

const count = arr => arr.reduce((a, v) => (a[v] = (a[v] || 0) + 1, a), {});
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:
Converts an array into an object showing how many times each element appears.

Example:

const fruits = ["apple", "banana", "apple", "orange", "banana"];
console.log(count(fruits)); 
// { apple: 2, banana: 2, orange: 1 }
Enter fullscreen mode Exit fullscreen mode

9. Check If an Object Is Empty

const isEmpty = obj => Object.keys(obj).length === 0;
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:
A clean, modern way to verify if an object has no properties.

Example:

console.log(isEmpty({})); // true
console.log(isEmpty({name: "JS"})); // false
Enter fullscreen mode Exit fullscreen mode

10. Capitalize the First Letter of a String

const capitalize = str => str.charAt(0).toUpperCase() + str.slice(1);
Enter fullscreen mode Exit fullscreen mode

Why it’s useful:
A simple one-liner that turns "hello" into "Hello" — great for UI text formatting.

Example:

console.log(capitalize("javascript")); // "Javascript"
Enter fullscreen mode Exit fullscreen mode

Bonus Tip: Combine One-Liners with Utility Functions

You can collect your favorite one-liners into a utility.js file and reuse them across your projects.
This helps keep your main logic readable and your helper code ultra-efficient.

Example:

// utils.js
export const rand = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
export const isEmpty = obj => Object.keys(obj).length === 0;
export const unique = arr => [...new Set(arr)];
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

JavaScript is powerful because of its flexibility — and mastering one-liners is part of writing clean, modern, and expressive code.

By using these shortcuts, you’ll not only save time but also write code that feels elegant and easy to maintain.

  • Try using one or two of these in your next project.
  • Add them to your snippets library.
  • And share this post with your JS friends who love writing smart code.

Top comments (1)

Collapse
 
studentluxe profile image
Student Luxe

Like this App!