The spread operator is a new addition to the features available in the JavaScript ES6 version. The spread operator is used to expand or spread an iterable or an array.
1. Use of Spread Operator
The spread operator (in form of ellipsis) can be used in two ways:
- Initializing arrays and objects from another array or object
- Object de-structuring
The spread operator is most widely used for method arguments in form of rest parameters where more than 1 value is expected. A typical example can be a custom sum(...args)
method which can accept any number of method arguments and add them to produce the sum.
function sum(...args: number[]) { //iterate args array, add all numbers and return sum }
2. Spread Operator Examples
2.1. Initialize array from another array
We can use the spread operator to create arrays from existing arrays in the given fashion.
let origArrayOne = [ 1, 2, 3]; //1,2,3 let origArrayTwo = [ 4, 5, 6]; //4,5,6 //Create new array from existing array let copyArray = [...origArrayOne]; //1,2,3 //Create new array from existing array + more elements let newArray = [...origArrayOne, 7, 8]; //1,2,3,7,8 //Create array by merging two arrays let mergedArray = [...origArrayOne, ...origArrayTwo]; //1,2,3,4,5,6
2.2. Initialize Objects from another Object
We can also use the spread operator to create objects from the existing objects in the given fashion.
let origObjectOne = {a: 1, b: 2, c: 3}; //{a: 1, b: 2, c: 3} let origObjectTwo = {d: 4, e: 5, f: 6}; //{d: 4, e: 5, f: 6} //Create new object from existing object let copyObject = {...origObjectOne}; //{a: 1, b: 2, c: 3} //Create new object from existing object + more elements let newObject = {...origObjectOne, g: 7, h: 8}; //{a: 1, b: 2, c: 3, g: 7, h: 8} //Create object by merging two objects let mergedObject = {...origObjectOne, ...origObjectTwo}; //{a: 1, b: 2, c: 3, d: 4, e: 5, f: 6}
2.3. Object Destructuring
The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.
function myFunction(x, y, z) { console.log( x ); console.log( y ); console.log( z ); } var parametersArray = [0, 1, 2]; myFunction(...parametersArray); //0, 1, 2
3. Spread Operator vs apply() Method
The JavaScript’s apply()
method calls a function with a given this
value, and arguments provided as an array
.
For example, in the below example, both highlighted function calls are equivalent. They both print the same output.
var numbers = [1, 2, 3, 4, 5]; console.log.apply(console, numbers); //1 2 3 4 5 console.log("1", "2", "3", "4", "5"); //1 2 3 4 5
Spread operator (part of ECMAScript 6) is a better version of the apply()
method. Using the spread operator, we can write the above statement as given below.
var numbers = [1, 2, 3, 4, 5]; console.log(...argsArray); //1 2 3 4 5
Happy Learning !!
Ref: Mozilla Docs