Search⌘ K

Uses of the Spread Operator

Explore how to use the JavaScript spread operator with named and rest function parameters, arrays, objects, and constructors. Understand its role in creating concise, extensible code and maintaining immutable data structures. This lesson helps you improve argument handling, object copying, and array manipulation.

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:

Javascript (babel-node)
'use strict';
//START:CODE
const 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 argument name2. Then, the rest of the values in the spread argument go to the rest parameter.

📝Note: The now ...