Javascript Function Execution Context And Scope

Introduction

The execution context of a variable or function defines what other data it has access to and how it should behave.

Each execution context has an associated variable object.

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 Javascript 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 defined with var are created as properties and methods on the window object.

Declarations using let and const at the top level are not defined in the global context, but they are resolved identically on the scope chain.

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.

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.

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.

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.




PreviousNext

Related