Uses of the Spread Operator
Learn the different uses of the spread operator with other arguments, constructors, arrays, and objects with examples.
Mixing the spread operator with other arguments
In addition to mixing the spread operator with other discrete arguments, we can also mix the operator when the receiver has a mixture of named parameters and the rest parameter.
Example
Here’s an example to illustrate:
Press + to interact
'use strict';//START:CODEconst mixed = function(name1, name2, ...names) {console.log('name1: ' + name1);console.log('name2: ' + name2);console.log('names: ' + names);};mixed('Tom', ...['Jerry', 'Tyke', 'Spike']);//END:CODE
Explanation
- The function has two named parameters and one rest parameter.
- The caller is passing a separate stand-alone value
'Tom'
followed by a spread argument. - The stand-alone argument binds to the first parameter
name1
, and the first value within the spread argument binds to the second named argumentname2
. Then, the rest of the values in the spread argument go to the rest
Access this course and 1400+ top-rated courses and projects.