Javascript Scope

sachin yadav
GitStacks

--

Scope in javascript basically means that the accessibility of the Function, Object, Variable at the particular part of code. which means if a specific part of the code can access some variable or not.

The scope is of two types :
1. Global 2. Local

-> Global Scope: In javascript global scoped function, Variable, and object which can be accessed from anywhere in the code. (The value of the variable depends on the hoisting). In browser, this global scope refers to the “This” keyword or window Object

As we can see in the screenshot this variable can be accessed from anywhere in the file because it has the global scope.

-> Local Scope: Variables defined inside a function are in the local scope.Local scope is accessed only inside the function in which it is being declared.

Scope always depends on the context of the execution in which the function of the code is being executed. In general, Javascript has a different Execution context. Top of all it has a Global Execution Context. (GCE)

GCE is created when the program runs for the very first time and remains until the program is not stopped or terminated.

And other is Execution Context which is dependent on the function/code which is being executed

Like we have

When we call the foo() function a GCE is created and when bar() is called it creates another Execution Context inside the stack.

Every EC (Execution Context) have two parts

  1. Memory 2. Code

Memory is the part where all the local variables are stored and it has reference to the lexical environment of its parent scope.

In the example above when the Execution Context of the bar is created and it goes to log the variable ‘b’ it checks inside the local scope memory of EC. and then when it does not find here it checks with its lexical parent scope.

If it was also not there it would be checked to the Lexical environment of foo() which is Global EC and if it's also not there it throws a Reference Error.

With Example

Lexical Environment: lexical Environment is created when the execution context is created and it is a combination of the local memory of EC and reference to the Lexical Environment or parent.

Thanks for Reading. If any queries please comment down I will be more than happy to help :)

--

--