Block Scope in JavaScript
block is used to combine multiple JavaScript statement in one group. block is known as compound statement.{//this is a block}
so this group of multiple statements can be used in a placed where JavaScript expected a single statement. Ex.
like this, all statements are in group with it's {}. because if expects single statement like if(x == 2) true but we want to more statement so we need block.let x = 0if(x == 2){x = x + 1;console.log('it is not 0');}
Everyone says let and const are block scope. but Why?
This let b and let c is gone in block section and var a is goes to Global section. means let b and let c are store but in different in place. and we packed all this variable in block means inside {} so can we access this let and const variable in outside the block? obviously no! that’s why let and const are block scope.var a = 1;let b = 2;const c = 3;
we can access a bcz. this variable declare using var is a global scope.{var a = 10;let b = 100;const c = 1000;}console.log(a)
Post a Comment