Javascript Placement Series (Part 4)
What is a Block?
A Block is a compound statement which is used to group one or more statement. It groups the multiple lines and interprets as single line. Basically we can create Block with curly braces ( "{ }" ).
We use block where we need to write multiple statements but javascript require single statement.
What is Block Scope?
Block scope restricts the variable that are declared inside a specific block, from access by the outside of the block. Before ES6, javascript only had function scope and block scope. ES6 introduced let & const keywords, and these two keywords provide block scope.
Why let & const are block scope ?
If we declare a variable using let or const then these variable are not declare inside the global scope rather they are stored in some other location. They are stored to the memory which is reserved for this block only. Hence the scope of these variable are block. Once the execution of block is completed we cannot access those variable anymore. On the other hand if we declare a variable using var then that variable will be global scoped and wil be stored inside the global object. We will be able to access that variable inside or outside any block.
What is Shadowing ?
If we have same name variable declare before the block then the variable inside the block will shadow or override the variable that is already been stored.
Shadowing using var keyword
So, when we declare var keyword before outside any block then the variable is stored inside the global scope. Now when we initialize a variable inside the block it is also stored inside the global scope. Hence both the variable have the same name and type so they both would be pointing to one single variable, and because the variable declare inside the block the value of the variable will get updated or overridden.
Shadowing using let keyword
Usually, when we declare variable using let or const outside of any block or function it is stored in some other memory scope and not in global scope. Now when we declare a let variable inside a block it is stored in the memory location that is totally reserved for that block. Hence if both the variable have same name then if we access the variable inside block we only get the value that is declared inside the block and when we access the same name variable outside the block we get the other value which was declared globally.
What is lexical scope ?
Lexical scope is the ability for a function scope to access variables from the parent scope. Lexical Scope allows inner functions to access the scope of their outer functions