Home  >  Article  >  Web Front-end  >  iller JavaScript Hacks Wish I Knew Soon

iller JavaScript Hacks Wish I Knew Soon

Susan Sarandon
Susan SarandonOriginal
2024-11-23 13:35:11128browse

iller 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';

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]; 

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];

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])];

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';

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

The above is the detailed content of iller JavaScript Hacks Wish I Knew Soon. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn