The three dots features is ES6 feature. It can be used in two different ways :
1. Rest Parameter : In javascript function, we can pass any number of parameters. The rest parameter collects all remaining elements into a array. It packs multiple to one.
function add(...args) {let result = 0;
for (let arg of args) result += arg;return result } add(1) // returns 1add(1, 2, 3, 4, 5) // returns 15add(1,2) // returns 3
This will fail :
function add(...args, x) {let result = x;for (let arg of args) result += arg;return result }//results error
This work as the rest operator can be used to collect only the rest of the arguments.
function add(x, ...args) {let result = x;
for (let arg of args) result += arg;return result } add(1) // returns 1add(1, 2, 3, 4, 5) // returns 15add(1,2) // returns 3
2. Spread operator : This allows iterables ( arrays or objects or strings ) to be expanded into a single argument. It unpacks one to multiple.
Pass array to arguments :
Reference :
Used with array :
let arrayOne = [1, 2, 3 ];
let arrayTwo = [ ...arrayOne, 4, 5, 6 ];
// Copy the arrayOne elements over to arrayTwo,
//and equals : [ 1, 2, 3, 4, 5, 6 ]
Pass array to arguments :
function add(a, b, c) {
return a + b + c ;
}
const args = [1, 2, 3];
add(...args);
Used with objects :
let address = { city : 'san diego', country : 'usa' };
let person = { ...address, name : 'san bhu' }
//address object cloned to person an merged it to another
// property ( can be used another spread operator to merge other object )
// called name,
//results : {city: "san diego", country: "usa", name: "san bhu"}
Reference :
Comments
Post a Comment