Rest & spread part 2

JavaScript Tutorial
ECMAScript 6
Rest & Spread
71
2/2
         

The Spread Operator



This operator is similar to the Rest Parameter, but it has another purpose when used in objects or arrays or function calls (arguments).

Spread in function calls


It is common to pass the elements of an arrayas arguments to a function. Before ES6, we used the following method:
function myFunction(w, x, y, z) {
console.log(w + x + y + z);
}
var args = [1, 2, 3];
myFunction.apply(null, args.concat(4));
Try It Yourself

ES6 provides an easy way to do the example above with spread operators:
const myFunction = (w, x, y, z) => {
console.log(w + x + y + z);
};
let args = [1, 2, 3];
myFunction(...args, 4);
Try It Yourself

Example:
var dateFields = [1970, 0, 1]; // 1 Jan 1970
var date = new Date(...dateFields);
console.log(date);
Try It Yourself

Spread in array literals


Before ES6, we used the following syntax to add an item at middle of an array:
var arr = ["One", "Two", "Five"];

arr.splice(2, 0, "Three");
arr.splice(3, 0, "Four");
console.log(arr);
Try It Yourself

You can use methods such as push, splice, and concat, for example, to achieve this in different positions of the array. However, in ES6 the spread operator lets us do this more easily:
let newArr = ['Three', 'Four'];
let arr = ['One', 'Two', ...newArr, 'Five'];
console.log(arr);
Try It Yourself

Spread in object literals


In objects it copies the own enumerable properties from the provided object onto a new object.
const obj1 = { foo: 'bar', x: 42 };
const obj2 = { foo: 'baz', y: 5 };

const clonedObj = {...obj1}; // { foo: "bar", x: 42 }
const mergedObj = {...obj1, ...obj2}; // { foo: "baz", x: 42, y: 5 }
Try It Yourself

However, if you try to merge them you will not get the result you expected:
const obj1 = { foo: 'bar', x: 42 };
const obj2 = { foo: 'baz', y: 5 };
const merge = (...objects) => ({...objects});

let mergedObj = merge(obj1, obj2);
// { 0: { foo: 'bar', x: 42 }, 1: { foo: 'baz', y: 5 } }

let mergedObj2 = merge({}, obj1, obj2);
// { 0: {}, 1: { foo: 'bar', x: 42 }, 2: { foo: 'baz', y: 5 } }
Try It Yourself

Shallow cloning or merging objects is possible with another operator called Object.assign().

Comments