Javascript Function Default Parameter Values Scope

Introduction

Defining multiple parameters with default values is like declaring variables sequentially using the let keyword.

Consider the following function:

function display(name = 'CSS', numerals = '123') {
    return `Input ${name} and ${numerals}`;
}
console.log(display());//from  ww w  . j a v  a 2  s. com

The default parameter values are initialized in the order listed.

We can think of it as behaving similar to the following:

function display() {
    let name = 'CSS';
    let numerals = '123';

    return `Input ${name} and ${numerals}`;
}

The following example works:

function display(name = 'CSS', numerals = name) {
    return `Input ${name} and ${numerals}`;
}
console.log(display()); 

This would throw an error:

// Error 
function display(name = numerals, numerals = '123') { 
   return `Input ${name} and ${numerals}`; 
} 



PreviousNext

Related