When a JavaScript program is executed, the JavaScript engine creates execution contexts that are used to manage the program’s state and execution.
The first execution context that is created is the global execution context. This context is responsible for executing any code that is not contained within a function. It contains the global object, which provides access to built-in functions and variables, as well as any global variables declared within the program.
When a function is called, a new execution context is created for that function. This context is created on top of the current execution context, forming a stack of execution contexts. The new context contains the function’s arguments, variables declared within the function, and a reference to the outer (parent) execution context.
When the function has completed its execution, its execution context is removed from the stack and control is returned to the previous execution context.
Within a function, the this
keyword refers to the object that the function is a method of. If the function is not a method of an object, this
refers to the global object. In a browser environment, the global object is represented by the window
object.
In summary, the JavaScript engine creates execution contexts to manage a program’s state and execution. The global execution context is created first and is responsible for executing any code that is not contained within a function. When a function is called, a new execution context is created for that function. The this
keyword refers to the object that the function is a method of, or the global object if the function is not a method of an object. In a browser environment, the global object is represented by the window
object.