Menu
Coddy logo textTech

Spread and Rest

Lesson 5 of 9 in Coddy's Tricky parts of Modern Javascript (ES6+) course.

In Javascript , a single <strong>...</strong> (three dots) operator can be used for two types of work !

Spread

<strong>...</strong> can be used to pass elements of an array , as separate parameters to a function

let array1 = [1,2,3];
Math.max(...array1); // exactly same as Math.max(1,2,3)

It is also used to copy an array into another array or copy properties of one object literal into another object literal.

let arr1 = [1,2,3];
let arr2 = [6,7,8];
let final = [...arr1, 4, 5, ...arr2]; // [1,2,3,4,5,6,7,8]

let obj1 = {name:"Shubham"};
let obj2= {work: "Software Development"};
let finalObj = {...name,...work}; // {name:"Shubham",work:"Software Development"}

Rest

<strong>...</strong> can be used to collect all the remaining (rest) parameters of a function , into an array

function sum(a,b,...rest){
	console.log("rest parameters : ", rest); 
}

sum(1,2,3,4,5,6) //rest parameters: [3,4,5,6]

Rest parameters should always be the last parameters . function sum(a, ...rest , b){ } will not work.

challenge icon

Challenge

Easy

Write a function to copy properties from both obj1 & obj2 and return the new object having properties of both the objects.

Try it yourself

function combineObjects(obj1, obj2) {
    // Write code here
}

All lessons in Tricky parts of Modern Javascript (ES6+)