function func(x = y, y = 2) {
return [x, y];
}
func(); // ReferenceError: y is not defined
func(1); // [1, 2]
As the code above implied, there is a hidden TDZ in the function parameters scope, which explains why the code below fails:
function func(arg) {
let arg = 1; // SyntaxError: Identifier 'arg' has already been declared
}
So function parameters should be declared with let
, but what confused me is :
function func(arg) {
var arg = 1;
console.log(arg); // 1
}
this code works fine.
Why you can redeclare variables using var
? How does Javascript declare function parameters?
edit:
I know exactly you can't use let to redeclare a variable. The question here is if function parameters is declared using let
, so:
function func(arg) {
var arg = 1;
}
is like:
let arg; // arg parameter declares here
var arg = 1; // func body
and why this can run without an exception?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…