Scopes in JavaScript

Wednesday, February 25, 2015

Scopes in JavaScript is the access/visibility of a variable at any particular point in a program. Scopes (Lexical Scopes) are just the way how variables in different parts of the program are accessible from different other parts of the program.

Variables can be in global or local scope (i.e. inner scope, and there can be many inner levels). The inner levels can always have access to variables from outer levels, but when it comes to objects the case is different. Let’s not involve objects for now and get confused.

Global Scope

When a variable is declared in Global scope it is available to all parts of the program.

In above code the variable global is accessible from any where in the program.

Local Scope

When a variable is defined inside of a function definition in a program, then that variable is in local scope i.e. it is available only inside the function in which it is defined in.

In the above code, local variable will not be available outside of the foo() function scope.

Variables defined within the function can be accessed inside of a function that is defined within the outer function.

In the code shown above, the inner function baz() has access to all the variables in foo() scope and also in global scope.

The inner scopes will have access to variable that is in the outer scope next to it and it continues till it reaches the global scope.

When declaring variable inside of function, don’t forget to use the var keyword. If not then the variable will be bound to the global scope.

Scope Circle
Scope Circle

When programming with object, the properties and functions of the object are bound to the object. The availability of the object itself is based on where the object is present in the program.

Execution Context/In Memory Scope

Executions context or In Memory scope is the scope built along upon the execution of the program, while lexical scope is built when the program is typed. In memory scope is where storage structures are built to store the variables that we declare in our program. Unlike lexical scope, in memory scope is not accessible to the programmer and is based on the program that is being executed.