Spread parameter

A spread parameter is using the same syntax ... ellipsis as the REST parameters, but it is used differently. It's not used as a parameter inside of a function, but rather inside the function body. 

Let's illustrate what that means:

var newItem = 3;
var oldArray = [ 1, 2 ];
var newArray = [
...oldArray,
newItem
];
console.log( newArray )

This would output:

1,2,3

What we do here is add an item to an existing array without changing the old array. The oldArray variable still contains 1,2, but the newArray contains 1,2,3. This general principle is called immutability, which essentially means don't change, but rather create a new state from the old state. It's a principle used in functional programming both as a paradigm, but also for performance reasons.

You can also use a REST parameter on objects; yes, really. You would write it like this:

var oldPerson = { name : 'Chris' };
var newPerson = { ...oldPerson, age : 37 };
console.log( newPerson );

The result from running this code is:

{ name: 'Chris', age: 37 }

A merge between the two objects. Just like with the example of the list, we would not change the previous variable, oldPerson. A newPerson variable would take the information from oldPerson, but add its new values to it. Looking at the ES5 code you can see why:

var __assign = ( this && this.__assign ) || Object.assign || function(t) {
for (var s, i = n, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call( s, p )) {
t[ p ] = s[ p ];
}
return t;
};
var oldPerson = { name : 'Chris' };
var newPerson = __assign({}, oldPerson, { age: 37 });
console.log( newPerson );
}

What's happening here is that an assign function is being defined. Said function loops the keys of oldPerson variables and assigns those to a new object and lastly adds the content of the newPerson variable. If you look at the preceding function, it either defines a function that does this or it uses Object.assign, which is part of ES6 standard, if available.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset