The concept of execution context, referred to as context for simplicity, is of the utmost importance in JavaScript. 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. Depending on the host environment for an ECMAScript implementation, the object representing this context may differ. In web browsers, the global context is said to be that of 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 is not 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 functions has finished executing, the stack is popped, returning control to the previously executing context. This facility controls execution flow throughout an ECMAScript program.
When code is executed in a context, a scope chain of variable object 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.
Identifiers are resolved by navigating the scope chain in search of the identifier name. The search always begins at the front of the chain and proceeds to the back until the identifier is found.( if the identifier is not found , typically an error occurs. )
var color='blue';
function changeColor(){
if(color==='blue'){
color='red';
}else{
color='blue';
}
}
changeColor();
In this simple example, the function changeColor() has a scope chain with two objects in it : its own variable object( upon which the arguments object is defined ) and the global context's variable object.