简体   繁体   中英

Variable reassignment in if statement not throwing error

Why does the code below doesn't throw a warning/error about variable re-assignment?

I spent a good amount of time debugging something like this because of the trailing comma.

When the code inside the else statement is moved outside of the if scope, it throws the proper error.

Any explanation would be great.

 let a if (false) { // Nothing } else { const b = 100, a = 10 } console.log(a) // undefined 

Let and const variables are not hoisted and are created in block scope.

So in your code, you are creating another variable a which is a const. and once scope is over, it will again point to a that is outside.

For example, if you try to reassign it in the same block, it will throw error as you cannot change value of const.

 let a if (false) { // Nothing } else { const b = 100, a = 10 a = 2; } console.log(a) // undefined 


As pointed out by Bergi , all variables are hoisted. But they are hoisted in a way to give impression that they are not hoisted. You can read full description here: Are variables declared with let or const not hoisted in ES6?

Why does the code not throw a warning/error about variable re-assignment?

Because you are not re-assigning a variable (which is what you actually wanted, assign the let a variable), you are re-declaring it with that const - and that in a different scope (in this case, the else block). If you had re-declared it in the same scope (eg let a; const a = 5 ) it would have thrown an error indeed. A shadowing declaration (that hides an existing names) in an inner scope is not an error, it is in fact necessary for local scopes to work and not be affected by their surroundings.

If you want to get a warning about this, use a linter that has a rule against shadowing declarations, eg in ESLint .

In else condition, a is re declared as const.So whatever the value (u assigned 10) within in else condition. you have to put ; at end of b declaration. otherwise a will be declared as const.So, a value is undefined in the outside of else condition.

 let a if (false) { // Nothing } else { const b = 100; a = 10 } console.log(a) 

in that case, it is because it never gets into the else statement, it is always false.

I usually use alert(string); to debug and know the value of variables, try one at the beginning of the if, or use console.log()

I also recommend you to read the following regarding let or var: What's the difference between using "let" and "var" to declare a variable? .

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