JS Lecture Notes : Scope (Function Scope & Block Scope)
Consider the next example :-
Every function create a different scope that hide its variables which is an intentional design principle of good software.
In the next example , the function is surrounded by the blue brackets , that form a block scope so this block could belong to any part of the code with its local variables without collision.
Starting from ES3 try/catch structure has a block-scope in the “catch” clause.
If you tried to use this variable out of “catch” scope you will get a Refernece error.
The “let” keyword
In ES6, the “let” keyword (a cousin to the “var” keyword) is introduced to allow declarations of variables in the scope of whatever block; In other words, “let” implicitly hijacks any block's scope for its variable declaration.
However, declarations made with “let” will not hoist to the entire scope of the block they appear in. Such declarations will not observably "exist" in the block until the declaration statement.
As you can see in the example “console.log(x);” is not in the forward scope of “let” so you will get a ReferenceError .
ES6 also intoduced “const” which also creates a block-scoped variable, but whose value is fixed and if you tried to change that value at a later time results in an error.