Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
497 views
in Technique[技术] by (71.8m points)

ecmascript 6 - How does Javascript declare function parameters?

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

there is a hidden TDZ in the function parameters scope

Yes indeed. Have a look here for some more examples.

How does Javascript declare function parameters?

As parameters - see here for a step-by-step explanation. They're neither the same as let nor the same as var, they have their own semantics. ES6, which introduced default initialisers, gave them the same TDZ limitations as in let to catch more programmer mistakes.

Why you can redeclare variables using var?

Because until ES5, redeclaring a variable was not an error condition, and this behaviour needed to be preserved to not break the web. It could only be introduced for new features, like let and const - or argument lists that use default initialisers, try function x(bar, bar) {} vs function x(bar, bar=1){}.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...