The spread operator ... has been introduced with ES2015 and is used to expand elements of an iterable (like an array) into places where multiple elements can fit.
arr2 the first element is an array because arr1 is injected as is into arr2. But what we want is arr2 to be an array of letters. To do so, we can spread the elements of arr1 into arr2.
In function parameters, we can use the rest operator to inject parameters into an array we can loop in. There is already an arguments object bound to every function that is equal to an array of all the parameters passed into the function.
But let's say that we want this function to create a new student with its grades and with its average grade. Wouldn't it be more convenient to extract the first two parameters into two separate variables, and then have all the grades in an array we can iterate over?
That's exactly what the rest operator allows us to do!
functioncreateStudent(firstName,lastName,...grades){// firstName = "Nick"// lastName = "Anderson"// [10, 12, 6] -- "..." takes all other parameters passed and creates a "grades" array variable that contains themconstavgGrade=grades.reduce((acc,curr)=>acc+curr,0)/grades.length;// computes average grade from gradesreturn{firstName:firstName,lastName:lastName,grades:grades,avgGrade:avgGrade}}conststudent=createStudent("Nick","Anderson",10,12,6);console.log(student);// {// firstName: "Nick",// lastName: "Anderson",// grades: [10, 12, 6],// avgGrade: 9,33// }
Note: createStudent function is bad because we don't check if grades.length exists or is different from 0. But it's easier to read this way, so I didn't handle this case.
Object properties spreading
For this one, I recommend you read previous explanations about the rest operator on iterables and function parameters.
constmyObj={x:1,y:2,a:3,b:4};const{x,y,...z}=myObj;// object destructuring hereconsole.log(x);// 1console.log(y);// 2console.log(z);// { a: 3, b: 4 }// z is the rest of the object destructured: myObj object minus x and y properties destructuredconstn={x,y,...z};console.log(n);// { x: 1, y: 2, a: 3, b: 4 }// Here z object properties are spread into n