Javascript ES6 … 3 dots 101

Thu Jun 21 2018

ES6 3 dots syntax has a lot of awesome tricks to do a lot of tricks and variable manipulations.

As it can save you many lines of code it will help you with your functional programing as it doesnt mutate the changed variable.

Javascript actions without mutating

extract a key from object

const obj = {a:1, b:2, c:3};
let {c} = obj;
console.log(c); //3

remove keys from object without mutating

let {b,...rest} = obj;
console.log(obj); // {a:1, b:2, c:3}
console.log(rest); // {a:1, c:3}

add key to object

const added_d_key = {...obj, d: 4};
console.log(obj); // {a:1, b:2, c:3}
console.log(added_d_key); // {a:1, b:2, c:3, d:4}

update key in object

const update_c_key = {...obj, c: 100};
console.log(obj); // {a:1, b:2, c:3}
console.log(update_c_key); // {a:1, b:2, c:100}

array tricks

const arr = [1,2,3];

 add element to array
const arr_added = [...arr, 4];
console.log(arr);
console.log(arr_added);

remove element from array

const indexToRemove = 1;
const part_arr = [
    ...arr.slice(0, indexToRemove),
    ...arr.slice(indexToRemove + 1)
];
console.log(arr);
console.log(part_arr);

function params unspread

function destructObj({a, b}) {
    console.log(a, b); // 1 2
}
destructObj(obj);

function params “join”

function join_args(...joined_args) {
    console.log(joined_args); // [ 1, 'a', 2, 'b' ]
}
join_args(1,'a',2,'b');

break array items to function variable

function break_array_to_func_vars(a, b) {
console.log(a, b); // 1 2
}
break_array_to_func_vars(...[1,2]);