简体   繁体   中英

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

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 '

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM