Do you know why you need to enclose your if statement and others as well in curly braces whenever you want to write multiple statements inside it?
When asked in an Interview question the question that “What is Block?”.
Most people often reply with let and const are block-scoped. While it’s true that’s not what is being asked, the question is what is a block
Now that we understood what Block is. let's dive into knowing what is block-scoped and how their nature differs.
Let us move towards the statement we mentioned earlier
Let and const are block-scoped.
But before understanding what it means let us first understand how var behaves and what is the scope var.
As you can see above the var defined under if statement made changes to one declared above it. This can only happen if both the declaration refers to the same variable.
This means that var declared above is defined at the global/window scope.
Var is function-scoped.
Which means var’s scope is defined by function, and if the function isn’t there, it is defined in the global scope.
You must be feeling that var has got the potential to created unexpected behaviour and might introduce hard to fix bugs. For the same reason let and const were introduced.
Understanding let and const
Let and const are block-scoped which means the scope of access of variable defined inside a block remains inside the block and cannot be accessed outside of the block.
The difference between let and const is, let can be reassigned whereas const cannot which means const is more stringent than let.
You might be confused with everything that I have thrown at you. Let’s take an example.
You see that variable declared inside the block made no effect on the variable declared outside of the variable.
Now let's see how it is stored inside our browser to make sure you understand it well enough.
Now when I set debugger on line 2 and capture an image at that instance of Scope in our browser that shows that our variable a is under global scope while let and const are inside block-scoped.
Which means that during our var example when we declared the variable inside block it actually accessed our global variable and changed its value which resulted in strange behaviour.
Now that you have got the feel of it. You can always challenge your understanding by re-declaring the variable inside the scope with let which is declared as var in a wider scope and vice versa.
Now since you know how var, const and let behave, what do you think is most strict and which one is the least?
Yeah, you guessed it right, const being the most and var being the least.
Now you have armed yourself with enough knowledge to answer any question that interviewer throws at you in concepts regarding block, block-scoped.
Now let me challenge you with two snippets to test your understanding (it’s always fun and extremely important.)
What do you think caused such behaviour? Try thinking in terms of strictness.