Execution Context in JavaScript - Exercise 2

JavaScript prepares bindings, stores function declarations, sets up scope links, and determines this before executing statements.

console.log(score); // undefined
var score = 100;
// var score was prepared before execution.

JavaScript evaluates expressions, assigns values, and runs statements from top to bottom.

var count; // prepared as undefined
count = 3; // assigned during execution
console.log(count);

Function declarations are stored during context creation, so the complete function is available when execution begins.

sayHello();
function sayHello() {
  console.log('Hello');
}

var is initialized to undefined; let and const remain in the Temporal Dead Zone until execution reaches their declarations.

console.log(a); // undefined
// console.log(b); // ReferenceError
var a = 1;
let b = 2;

It is the period between entering a scope and executing a let or const declaration, during which accessing the binding throws a ReferenceError.

{
  // console.log(token); // TDZ
  const token = 'ready';
  console.log(token);
}

JavaScript checks the current environment first, then follows outer environment references until it finds the name or reaches the global scope.

const theme = 'dark';
function render() {
  const label = 'Menu';
  return `${theme}: ${label}`;
}
console.log(render());

The returned function retains a reference to the outer environment, so the captured binding remains reachable.

function createCounter() {
  let count = 0;
  return () => ++count;
}
const next = createCounter();
console.log(next(), next());

Only the variable binding is prepared. The function value is assigned when execution reaches the assignment.

// greet(); // TypeError: greet is not a function
var greet = function () {
  console.log('Hi');
};
greet();