The code execution scope in JavaScript is a very important aspect of programming. The structure of a typical JavaScript scope is highlighted and explained below.

Context

A context pertains to the object of the script. A this keyword defines the context of the script, which references the methods and access the variables, in currently executing code.

Scope

A scope is related to the function being executed. A scope defines the function block in which variables, objects and methods can be accessed. A scope can be local scope, global scope, and block scope.


Pictorial representation of JavaScript scopes.

 

 

 

 

 

 

 

 

 

 

 

 

Fig: Pictorial representation of JavaScript scopes

Global scope

Any statements declared outside a function is said to be global. A this keyword refers to a global object. The "greet" variable is in the global scope in above example. If we use any variable without declaring it, it becomes automatically global. That is, if we add any statement "age=34"; in function sayHello() without declaring age, it becomes a global value.

NOTE: The global variables are deleted when we close the page.

Local scope

Statements declared inside the function are said to be in local scope. Value of this keyword in local depends on the mode it is used in. If the code is not in strict mode, this refers to the object which defaults to global object or the HTML Element it is calling. If the code is in strict mode, this refers to the value set before entering the function. If it is not set to any value, it remains undefined.

NOTE: The local variables are deleted when we close the page.

Example of a local scope in JavaScript

function foo(){
    return this;
}
document.write(foo() === window); //true

function boo(){
    “use strict”;
    return this;
}
document.write(boo() === undefined); //true;

Block scope

This is a scope for a block of code inside any condition statement. The variable defined inside block statement should not be accessible outside. However this scope is supported in JavaScript from ECMA Specification 6 using keyword let. Currently, variable defined inside the block can be accessed outside

 

To read more about Block scope follow this link!

 

›› go to examples ››