Scope, For Your { } Only

Scope, For Your { } Only

ยท

3 min read

The scope is one of the important concepts in JavaScript, it manages the availability of variables. If you would like to code in JavaScript, you must understand the scope.

Scope

The Scope is the accessibility of variables, functions, and objects in some particular part of your code during runtime. In JavaScript, Scopes are created by code blocks, functions, etc.

"Scope is a policy that manages the accessibility of variables."

Why is Scope Needed?

  1. Scope Provides some level of security to our code. i.e variables can be accessed from a particular part of your code

  2. It also reduces the namespace collisions. i.e, we can use the same variable names in different scopes.

Types of Scope

1) Global Scope - This is the outermost scope, any variable that's not inside any function or block is inside the global scope. It can be accessed from anywhere in the program.

Ex: 1.1

global_scope.png 2) Function or Local Scope - It defines the boundary of a variable, outside of that boundary it cannot be accessed. Variables declared inside the function having local scope i.e they can be used inside the function boundary only.
Ex: 1.2 local_scope.png 3) Block Scope - A code block (code between curly braces) in JavaScript defines a scope for variables declared using let and const, unlike var variables they can be scoped to the nearest pair of curly braces. i.e that can't be accessed outside of that pair of curly braces.
Ex: 1.3
block_scope.png 4) Lexical Scope - It defines function accessibility, A function can access anything which is available in its lexical environment it does not matter whether that function is physically present or not. Lexical Environment - The environment where the function is physically available is called the lexical environment.
Ex: 1.4

In example 1.4, function 'c( )' has a lexical environment of a function ' a( )' which has a lexical environment of Global Execution which has a lexical environment of null i.e GE has no lexical environment.

Due to the lexical environment, function 'c( )' has the access to variable b because variable b is lexically available to function 'c( )'.

it works like this way if 'c( )'has a lexical environment of function 'a( )' then function 'a( )'s' all lexical environment is also available to 'c( )' but the opposite is not true i.e child having access to all its parent lexical environment but the parent doesn't have access to its child lexical environment.

How JavaSciprt assign the value of variables?

Javascript always start looking for variable's value from local to global, Example 1.4 line no 4 Js engine will first search value of 'b( )' in his local environment i.e inside function 'c( )' if it is not available then it will look in its lexical environment i.e inside function 'a( )' and if it is not available there also it will keep checking in all the lexical environment which available to 'c( )'.

image.png

References: