JS Lecture Notes : Scope (Function Scope & Block Scope)

Consider the next example :-

Function Scope

In Javascript, functions are the most common unit of scope ;between every {} is a new scope , as you can see ‘a’ had been declared in the first function with value of 2 , and with a value of 3 in the second function without any collision.

Every function create a different scope that hide its variables which is an intentional design principle of good software.

Block Scope

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.

try/catch scope

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.

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.