Execution Context in JavaScript - Exercise 1
It is the environment JavaScript creates to run code, including its variables, functions, scope information, and this value. This separation helps explain which values and bindings are available at each point in the program.
const message = 'Hello';
// message is created and used inside an execution context.
console.log(message);It is the initial context created for top-level script code. A script has a global context for its realm. The example shows how that rule affects the values you can read or call.
var siteName = 'Simply JavaScript';
function showSite() { console.log(siteName); }
// These declarations belong to the global code.A new function context is created every time a function is called. This separation helps explain which values and bindings are available at each point in the program.
function add(first, second) {
// A new context is created for this call.
return first + second;
}
add(2, 3);Yes. Each call gets a separate context and its own local bindings. The example shows how that rule affects the values you can read or call.
function greet(name) {
const message = `Hello, ${name}`;
console.log(message);
}
greet('Ava');
greet('Mina');The call stack tracks active execution contexts in last-in, first-out order. This separation helps explain which values and bindings are available at each point in the program.
function outer() { inner(); }
function inner() {
// Stack: global -> outer -> inner
}
outer();For a regular method call, this is the object before the dot. This separation helps explain which values and bindings are available at each point in the program.
const user = {
name: 'Ava',
getName() { return this.name; }
};
console.log(user.getName());A plain regular function call has this set to undefined in strict mode. This separation helps explain which values and bindings are available at each point in the program.
'use strict';
function inspectThis() {
return this;
}
console.log(inspectThis()); // undefinedIt links a context to its surrounding scope so JavaScript can look up variables outside the current function. This separation helps explain which values and bindings are available at each point in the program.
const prefix = 'ID';
function format(value) {
return `${prefix}-${value}`;
}
console.log(format(7));A function execution context tracks its parameters, local bindings, and connection to its outer environment while the function runs. It also determines the function's this value.
function greet(name) {
const message = `Hello, ${name}`;
return message;
}
console.log(greet('Ada'));Calling a function pushes its execution context onto the call stack. Returning from the function removes that context, allowing the caller's context to continue.
function outer() {
inner();
}
function inner() {
console.log('top of the stack');
}
outer();