+ 3

Am I the only one Still struggling with SCOPE of VAR, LET & CONST? Watch these....

there are lot of confusions but suppose this, if(true){ let y= "cousin"; console.log(y); } console.log(y); //cousin //reference Error it's fine cause let is block scope! but here, let x= "dad"; if(true){ x= "mom"; console.log(x); } console.log(x); //mom //mom let x is updated in to the block scope, Why the second console follows the updated scope? instead of " dad" from previous local scope? if this is gonna follow the updated variable from outside of the block scope then again my first code, why the second console is reference Error? can't evaluate the variable from block scope? sorry if you find it very stupid, I'm really new but very passionate to know them from heart & soul

3rd Oct 2018, 9:25 AM
The Code Breaker
The Code Breaker - avatar
3 Antworten
+ 2
The scope of the x in your second example includes the if block. So it can be accessed and modified there. Anything declared with "let" inside is not accessible outside. But anything declared outside (and not enclosed by a different block/function) can be accessed inside. I like to think of functions, blocks etc as nodes of a tree: a / \ b c / \ / \ d e f g / / \ \ /\ h i j k l m A child node can access anything from its ancestor node. For example, d has access to variables declared previously in a, b, and itself, but not those in h or c. Aside: this is why global variables can be dangerous. They can be changed by any function anywhere, and may be hard to keep track of. Some more reading: https://www.w3schools.com/js/js_let.asp
3rd Oct 2018, 12:35 PM
Kishalaya Saha
Kishalaya Saha - avatar
+ 2
My explanation: In the second case the variable is declared outside of the conditional check. In the if-statement it's replaced with "mom" and then printing it. But you changed x to "mom" (declared outside of the conditional check => again printing "mom".
3rd Oct 2018, 9:46 AM
TheWh¡teCat 🇧🇬
TheWh¡teCat 🇧🇬 - avatar
+ 2
D⚽⚽⚽⚽7⃣7⃣7⃣ that is what my question is, how am I able to change the outsider declared variable from the inside block scope in the if-statements which is followed by the second console outside the block scope?
3rd Oct 2018, 10:02 AM
The Code Breaker
The Code Breaker - avatar