JavaScript Scope and Execution Context

By:    Updated: January 24,2017

The execution context of a variable or function defines what other data it has access to, as well as how it should behave. Each execution context has an associated variable object upon which all of its defined variables and functions exist. This object is not accessible by code but is used behind the scenes to handle data.

 

The global execution context is the outermost one.In web browsers, the global context is the window object, so all global variables and functions are created as properties and methods on the window object. When an execution context has executed all of its code, it is destroyed, taking with it all of the variables and functions defined within it (the global context isn't destroyed until the application exits, such as when a web page is closed or a web browser is shut down).

 

Each function call has its own execution context. Whenever code execution flows into a function,the function's context is pushed onto a context stack. After the function has finished executing,the stack is popped, returning control to the previously executing context. This facility controls execution flow throughout an javascript program.

 

When code is executed in a context, a scope chain of variable objects is created. The purpose of the scope chain is to provide ordered access to all variables and functions that an execution context has access to. The front of the scope chain is always the variable object of the context whose code is executing.If the context is a function, then the activation object is used as the variable object. An activation object starts with a single defined variable called arguments. The next variable object in the chain is from the containing context, and the next after that is from the next containing context. This pattern continues until the global context is reached; the global context's variable object is always the last of the scope chain.

<script type="text/javascript">
var fs_age = 2;

/*
 * The function has a scope chain with two objects in it: 
 *     1. local context object: its own variable object (upon which the arguments object is defined)
 *     2. global context object: the global context's variable object.
 */
function addAge()
{
	//fs_age is accessible inside the function, because it can be found in the scope chain
	if(fs_age >=0 )
	{
		fs_age++;
	}
	else
	{
		fs_age = 1;
	}
}

addAge();

alert(fs_age);
</script>
<script type="text/javascript">
var salary_init = 10000;

function increaseSalary()
{
    var job_position = "developer";

    function increaseBasedOnRate()
    {
        var salary_rate = 0.1;

        //The "job_position" variable is in context of increaseSalary()
        if("developer" == job_position)
        {
            salary_rate = 0.2
        }

        //The "salary_init" variable is in global context
        var salary_result = salary_init * (1 + salary_rate);

        //both of "job_position" and "job_position" are fully accessible, because they are in parent execution contexts.
        //Thease can be think that an inner context can access everything from all outer contexts through the scope chain
        alert(salary_result); //12000
    }

    increaseBasedOnRate();

    //but the outer contexts cannot access anything within an inner context
    alert(typeof salary_rate); //undefined
}

increaseSalary();

alert(typeof job_position); //undefined
</script>

No Block-Level Scopes

In languages such as C, C++, and Java, the variable defined in flow-control statements would be destroyed after the statement is executed, but except in javascipt.

<script type="text/javascript">

var job_position = "developer";

//in if 
if("developer" == job_position)
{
	var salary_rate = 0.2;
}		
alert(salary_rate); //0.2

//in for
for(var i=0; i<10; i++)
{

}
alert(i); //10
</script>

Variable Declaration

When a variable is declared using var, it is automatically added to the most immediate context available. In a function, the most immediate one is the function's local context. If a variable is initialized without first being declared, itgets added to the global context automatically.It's advisable to always declare variables before initializing them.

<script type="text/javascript">
function addSalary(salary_init, salary_increase)
{
	var salary_sum = salary_init + salary_increase;

	//initialized but without first being declared(it isn't declared using var before initialized)
	salary_without_var_declared = salary_sum;

	return salary_sum;
}

var salary_result = addSalary(10000, 2000);

alert(salary_result); //12000

alert(typeof salary_sum); //undefined

alert(salary_without_var_declared); //12000
</script>
More in Development Center
New on Valinv
Related Articles
Sponsored Links