Saturday, August 10, 2019

Three dot operator (spread operator) in javascript

As the name of 'spread operator' implied, the three dot operator in javascript is mainly used to spread an array object into a list of elements. So that array object can be used in more general cases.

For example, in the below code, the numbers array object can use spread operator to convert it to three separate arguments for calling sum function
function sum(x, y, z) {
  return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));

Spread operator can also be used to combine elements from an array to form another array object, as shown below
var parts = ['shoulders', 'knees']; 
var lyrics = ['head', ...parts, 'and', 'toes']; 
// lyrics is: ["head", "shoulders", "knees", "and", "toes"]

Similar to above, spread can also be used to copy an array object to another one
var arr = [1, 2, 3];
var arr2 = [...arr]; // like arr.slice()
arr2.push(4); 
//arr2 is [1, 2, 3, 4]

Another use case of spread operator is copying object as shown below
ar obj1 = { foo: 'bar', x: 42 };
var clonedObj = { ...obj1 };
// clonedObj contains { foo: "bar", x: 42 }

No comments:

Post a Comment