DEV Community

thandhla
thandhla

Posted on

5 Killer JavaScript Hacks Wish I Knew Soon

Short-Circuit Evolution For Default Values

Skip the if-else for default values. Use a || for a cleaner, one-liner assignment.

//old way 
let userName;
if (userInput) {
 userName = userInput;
} else {
 userName = 'Guest';
}

//modern way
const userName = userInput || 'Guest';
Enter fullscreen mode Exit fullscreen mode

Swipe Variables Without a Temporary Variable

Use array destructuring to swap values in a single line, no temporary values are needed.

//old way
let temp = a;
a = b;
b = temp;

//modern way
let a = 1, b = 2;
[a, b] = [b, a]; 
Enter fullscreen mode Exit fullscreen mode

Output: a = 2 and b = 2

Clone an Array Quickly
Clone arrays with the spread operator for a simpler, more
intuitive method.

// old way
const clone = original.slice();

//modern way
const original = [1, 2, 3];
const clone = [...original];
Enter fullscreen mode Exit fullscreen mode

Easily Remove Duplicates from an Array
Remove duplicates using Set, turning it into a concise one-liner modern solution.

//old way
const uniqueArray = [];
for (let i = 0; i < array.length; i++)  {
  if (!uniqueArray.includes(array[i])) {
     uniqueArray.push(array[i]);
 }
}

//modern way 
const uniqueArray = [...new Set([1, 2, 2, 3, 4, 4])];
Enter fullscreen mode Exit fullscreen mode

Convert a String to a Number Quickly

Convert strings to numbers with the unary +operator for a
quick solution.

//old way
 const num = parseInt('12', 39);

//modern way
consst num = +'12';
Enter fullscreen mode Exit fullscreen mode

Conclusion
These modern JavaScript techniques provide cleaner, more efficient, and often more readable code. Using these one-liners and built-in functions simplifies complex logic, removes redundancy

Top comments (0)