Member-only story
20+ Powerful JavaScript One-Liners That Will Amaze You (With Examples!)
Save This
Nonmembers, click here
JavaScript is a playground for coders, and one-liners are like magic tricks — short, sweet, and surprisingly powerful. Whether you’re cleaning up code or impressing your teammates, these snippets can save the day. In this post, I’ll share over 20 amazing JavaScript one-liners, each with a practical example to show them in action. Let’s jump right in!
1. Swap Two Variables Without a Temp Variable
No more juggling temporary variables!
let a = 5, b = 10;
[a, b] = [b, a];
console.log(a, b); // 10, 5
Destructuring makes this swap silky smooth.
2. Generate a Random Number Between Two Values
Perfect for dice rolls or random IDs:
const random = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
console.log(random(1, 6)); // e.g., 4 (random between 1 and 6)
Try it for a quick game mechanic!
3. Check if a Number is Even
A modulo classic:
const isEven = num => num % 2 === 0;
console.log(isEven(8)); // true
console.log(isEven(7)); // false
Great for filtering or validation.
4. Remove Duplicates from an Array
Say goodbye to repeats:
const unique = arr => [...new Set(arr)];
console.log(unique([1, 2, 2, 3, 3, 4])); // [1, 2, 3, 4]
The Set object does all the heavy lifting.
5. Flatten an Array (One Level)
Untangle nested arrays:
const flat = arr => arr.flat();
console.log(flat([[1, 2], [3, 4]])); // [1, 2, 3, 4]
Need more levels? Use flat(2) for deeper nests.
6. Sum All Numbers in an Array
Add it up in one shot:
const sum = arr => arr.reduce((a, b) => a + b, 0);
console.log(sum([1, 2, 3, 4])); // 10