Javascript ES6 'let' and 'var' - unexpected behavior inside function with argument name matching redeclared variable

放肆的年华 提交于 2020-07-23 08:54:47

问题


Please note this is not duplicate of existing var vs let scope. I'm aware of the scope of var and let declarations and differences.

But below scenario I could not justify with the understanding I had with let and var difference.

In the below code, function foo accepts argument by name 'x' which has implicit let scope - as I cannot redeclare same variable name using let inside that function (uncommenting last line in function foo will throw JS error)

"use strict";

function foo(x) {
    console.log('Inside function x:', x);
    var x = 30; // 'x' redeclared overwriting argument/parameter 'x'
    console.log('Redeclared x:', x);
    // let x = 400; // uncommenting this line throws error even if you remove 'var x = 30;'
}

foo(100);
// global
let y = 100;
console.log('y:', y);
// var y = 300;

Executing the above code with two lines commented out works perfectly, and you can see the output as:

Inside function x: 100      index.js:4 
Redeclared x: 30            index.js:6
y: 100                      index.js:13

Uncommenting last line // var y = 300; will throw error.

Question is: Why redeclaring 'x' using 'var' inside function foo works but throws error when 'y' is redeclared in the global scope using 'var'


回答1:


The var declaration syntax is original to the language, and has fairly permissive rules. The let and const declarations are newer and more strict. You cannot re-declare variables with let or const no matter how they were declared in the first place. And if a variable is declared with let or const, a subsequent var declaration is also an error.

Declarations via let and const will not allow references to the variables before the declaration; that's why you get the error mentioned in your first example. In other words,

console.log(x);
let x = 0;

is an error because x is referenced before the declaration.



来源:https://stackoverflow.com/questions/56393446/javascript-es6-let-and-var-unexpected-behavior-inside-function-with-argume

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!