7 best JavaScript tricks you won’t be able to live without!
2 min readSep 6, 2019
1. Use destructuring to swap variables
let a = 1;
let b = 2;
console.log(a, b); // 1 2
[a, b] = [b, a]; // Magic swap!
console.log(a, b); // 2 1
2. Use the Spread operator to create a function that accepts a variable number of arguments
const add = (...numbers) => { // numbers is an array!
const sum = numbers.reduce((sum, n) => sum + n, 0);
return sum;
};
let sum = add(1, 2, 3);
console.log(sum); // 6
sum = add(1, 2, 3, 4); // as many as I want!!!
console.log(sum); // 10
3. Use the Spread operator to conditionally add a property to an object
const add = true;
const dontAdd = false;
const obj = {
a: 1,
...(add && { b: 2 }), // will be added
...(dontAdd && { c: 3 }) // will NOT be added!!!!
};
console.log(obj); // { a: 1, b: 2 }
4. Use the Spread operator to eliminate duplicate values in an array!
const a = [1, 1, 2, 2, 3, 3, 4, 4, 5, 5];
const uniques = [...new Set(a)]; // to Set and back to array!
console.log(uniques); // [ 1, 2, 3, 4, 5 ]
5. Destructure objects with defaults
let o = { a: 1 };
let { a, b = 2 } = o;
console.log(a, b); // 1 2 -> b is not undefined!
6. Destructure arrays with defaults
let array = [0, 1, 2];
let [a, b, c, d = 3] = array;
console.log(a, b, c, d); // 0 1 2 3 -> d is not undefined!
7. Filter falsy values
let array = [{}, [], 0, '', true, false, undefined, null, NaN];
console.log(...array.filter(Boolean)); // {} [] true
8. BONUS!!! Use JSON.stringify to pretty print in the console
let obj = { a: 1, b: 2, c: { d: { value: 3 } }, e: [1, 2, 3] };console.log(JSON.stringify(obj));
// Prints: {"a":1,"b":2,"c":{"d":{"value":3}},"e":[1,2,3]}console.log(JSON.stringify(obj, null, 2)); // Better!
/*
Prints:
{
"a": 1,
"b": 2,
"c": {
"d": {
"value": 3
}
},
"e": [
1,
2,
3
]
}
*/
9. BONUS BONUS! Use console.time
to track how long something takes
console.time('increment');
let n = 0;
for (let i = 0; i < 1000000; i += 1) {
n += i;
}
console.timeLog('increment'); // 0.349ms -> intermediate time
for (let i = 0; i < 1000000; i += 1) {
n += i;
}
console.timeEnd('increment'); // 0.808ms -> total time