3
4_constructing_rest_parameters_and_the_spread_operator
jason.zhu edited this page 2021-05-13 15:13:42 +10:00

Module 4: Constructing Rest Parameters and the Spread Operator

JS Feature works well with functions:

  • default parameters
  • rest parameters
  • spread operator

What are Default Paramters?

Default parameters allow developer provide default values to a parameter in a function

function sayHi(name = 'World') {
    console.log('Hello ' + name);
}
sayHi(); // Hello World
sayHi('John'); // Hello John
function sayHi(message, name = 'World') {
    console.log(message + name);
}
sayHi('Hello'); // Hello World
sayHi('Hi', 'John'); // Hi John

Note: default parameters always appear last in argument list

Constructing Rest Parameters

  • Rest parameter = a featuer of JS function that deal with multiple argument invocation
  • Like default parameter, rest parameter come later in function declaration (i.e. after any regular parameters)

e.g. of rest parameters

let setHi = function greet(...names) {
    names.forEach(name => console.log('Hi ' + name));
}
greet('Marry', 'John', 'James');    // Hi Mary
                                    // Hi John
                                    // Hi James

e.g. of rest parameters with other parameters.

let sayHi = function greet(message, ...names){
    console.log(message + ' everyone!');
    names.forEach(name => console.log('Hi ' + name));
}
greet('Welcome', 'Mary', 'John', 'James');  // Welcome everyone!
                                            // Hi Mary
                                            // Hi John
                                            // Hi James

Using the Spread Operator

Reference: How to use the spread operator in javascript

Spread Operator ...:

  • Opposite of rest operator.
  • Allow a function take an array as an argument and spread out elements to assign to individual function parameters
    • Rest parameters delcared in function parameter
    • Spread Operator used in function invokation as argument
function greet(person1, person2) {
    console.log('Hello ' + person1 + ' and ' + person2);
}
let names = ['John', 'Mary'];
greet(...names);

e.g. Spread Operator work with Rest Parameters

function display(char1, char2, char3, char4, ...others) {
    console.log(others);
    console.log(char1, char2, char3, char4);
}
let letters = 'abcdefgh';
display(...leters)