Reputation: 101
function test1(args){
let age = 23; // place debugger 1 here
var name = 'prajval';
}
test2();
function test2(...args){
let age = 23; // place debugger 2 here
var name = 'prajval';
}
test1();
scope at debugger 1: Local this: Window, age: undefined, args: undefined, name: undefined
Global
scope at debugger 2: Block age: undefined, name: undefined,
Local this: Window, args: []
Global
In test2() method when we used ...args as parameter that makes all other variable declarations of test2() method in block scope.
But I expected all of them (args and variable declaration) to be in the local scope itself just like test1().
Why this kind of different and unexpected behaviour is seen ??
Upvotes: 2
Views: 78
Reputation: 664548
JavaScript makes a distinction between complex parameter declarations and simple (ES5-compatible) parameter declarations. The former are creating an extra scope where only the parameters but not the variables declared in the body are visible. It does not make a difference for the rest parameter syntax in your example, but it does when there are default initialisers since those might contain closures (or worse, eval
):
var x = 1;
(function(f = (() => x)) {
var x = 2;
console.log(f()); // Which variable "x" will f() return? Surprise!
})();
There's a consideration to drop this distinction and just always use two separate scopes - they would only be observable in the debugger anyway. However this might confuse people who expect that function(x) { var x; }
has only a single x
variable, and implementations would want to optimise away the unreachable binding anyway.
Upvotes: 2