Default Parameter Scope
Version ES2015
Level: Intermediate
Normally, when function parameters are initialized in a function call, they’re scoped to the function body. However, when functions use default parameters, the parameters are given an additional, separate scope to be initialized in.
A function like this:
function paramScopes (param) {
let local = 2;
}
Can be seen as something like the following:
function paramScopes () {
let param = arguments[0];
let local = 2;
}
But given (note the added parameter default):
function paramScopes (param = 1) {
let local = 2;
}
What you get translates to something a little more like:
function paramScopes () {
let param = arguments[0] !== undefined ? arguments[0]: 1;
{
let local = 2;
}
}
This separation of parameters with local function variables allows parameters to refer to variables in the outer scope that may have a similarly named variable in the function body.
let value = 'outer';
function paramScopes (param = value) {
let value = 'inner';
console.log(param);
}
paramScopes(); // outer
If the param
parameter above would have been in the same scope as the rest of the function body, it would have referred to the inner value rather than the outer, and as a result would likely resolve to undefined
or throw an error due to the effects of hoisting.
More info:
More tips: JavaScript Tips of the Day