JavaScript is a popular programming language used for web development. One of the key concepts in JavaScript is execution context, which determines how code is run in JavaScript. In this article, we will take a closer look at JavaScript execution context and how it works.
In JavaScript, we typically assign variables and run functions. When we run a function by adding brackets to it, the JavaScript engine creates an execution context. The execution context is responsible for executing the function and keeping track of the function’s variables and scope.
function myFunction() {
var myVar = "Hello World!";
console.log(myVar);
}
myFunction(); // Executes the function, creating an execution context
When a function is called, the JavaScript engine creates an execution context and adds it to the call stack. The call stack keeps track of all the execution contexts that have been created. When a function finishes executing, its execution context is removed from the call stack.
function outerFunction() {
var outerVar = "Outer";
function innerFunction() {
var innerVar = "Inner";
console.log(outerVar + " " + innerVar);
}
innerFunction(); // Creates a new execution context for the inner function
}
outerFunction(); // Creates a new execution context for the outer function, adding it to the call stack
The global execution context is the first item on the call stack. It is created by the JavaScript engine when it starts running a JavaScript file. The global execution context provides two things: a global object and the ‘this’ keyword in JavaScript. The global object is the ‘window’ object in the browser.
console.log(window); // Outputs the global object in the browser (i.e. the window object)
To test if this assumption is correct, you can create an empty JavaScript file and run it in the browser. You will have access to the global object and the ‘this’ keyword without writing any code. This is because the browser creates a global execution context for you when it runs a JavaScript file.
function myFunction() {
console.log(this); // Outputs the global object in the browser (i.e. the window object)
}
myFunction(); // Executes the function, creating an execution context and referencing the global object with 'this'
In summary, whenever you run code in JavaScript, it is executed inside an execution context. The global execution context is the first context created and provides the global object and the ‘this’ keyword. The call stack keeps track of all the execution contexts and removes them when they finish executing. Understanding JavaScript execution context is essential for writing efficient and effective JavaScript code.