ES6 three dots (...)

Post 1Jun 2020

In ES6, JavaScript introduced three dots that is used for spread operator and rest operator.

Speared Operator: Speared Operator in object can be seem as taking all properties from an object and create a new object with these properties while allowing developers to overwrite these properties.

Eg:

const adrian = {
    fullName: 'Adrian Oprea',
    occupation: 'Software developer',
    age: 31,
    website: 'https://oprea.rocks'
};

const bill = {
    ...adrian,
    fullName: 'Bill Gates',
    website: 'https://microsoft.com'
};

Code Retrieved from (https://medium.com/@oprearocks/what-do-the-three-dots-mean-in-javascript-bc5749439c9a)

In this example, we create an object called adrian and put all its properties in to the object Bill then overwrite its 'fullName' and 'website'.

In array, the speared operator of three dots can be seem as the array1.concat(array2). Which copies all values in the array1 to a new array and merge these value with the array2. In this case the new array is the merge of array1 and array2.

Eg:

const numbers1 = [1, 2, 3, 4, 5];
const numbers2 = [ ...numbers1, 1, 2, 6,7,8]; // this will be [1, 2, 3, 4, 5, 1, 2, 6, 7, 8]

Rest Operator:

Three dots as rest operator can allow developers to create infinite value without worrying about the memory problem because the rest operator is like the lazy loading method, it won't generator all values at once instead of keep generating until the value you define.

Eg:

function sum(...numbers) {
    return numbers.reduce((accumulator, current) => {
        return accumulator += current
    });
};
sum(1, 2) // 3
sum(1, 2, 3, 4, 5) // 15

In this example we can see that the parameter 'numbers' allow user to define multiple arguments and 'numbers' will keep on generating until it reaches the top order.

(...) can be very useful in React because React promote developers to always use immutable values instead of mutable values, which requires developers to always make a new variable to copy original values and manipulate with the new variable.