Member-only story
10 JavaScript Programming Tips
🔄Tip 1: Use destructuring assignment to exchange variable values
let a = 1;
let b = 2;
[a, b] = [b, a];
console.log(a); // Output 2
console.log(b); // Output 1
This method makes it easy to swap the values of two variables without introducing a third variable.
🎁 Tip 2: Use array destructuring to obtain function return values
function getNumbers() {
return [1, 2, 3];
}
const [a, b, c] = getNumbers();
console.log(a); // Output 1
console.log(b); // Output 2
console.log(c); // Output 3
This way you can easily get multiple return values from a function.
🙋♂️ Tip 3: Use default parameters
function greet(name = 'Guest') {
console.log(`Hello ${name}!`);
}
greet(); // prints Hello Guest!
greet('John'); // prints Hello John!
This approach avoids checking in the function whether a parameter is passed and uses the parameter value if so, otherwise uses the default value.
🔗 Tip 4: Use the spread operator to merge arrays
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArr = [...arr1, ...arr2];
console.log(mergedArr); // prints [1, 2…