› Module 2: Control Flow › 2.3 Hoisting
M O D U L E

Module 2: Control Flow

Making decisions and repeating actions

2.1 if / else & switch

Control flow structures govern the branching path of execution based on conditional expressions. In JavaScript, conditionals evaluate the truthiness of expressions.

Figure 2.1: Truthy vs Falsy Decision Flowchart in JavaScript if (condition) Truthy or Falsy? Truthy Executes 'if' Code Block Falsy (0, '', null, undefined, NaN, false) Executes 'else' Fallback Block

Figure 2.1: Decision flow of an if/else branch evaluating boolean truthiness in JavaScript.

const userRole = "admin";

switch (userRole) {
  case "admin":
    console.log("Full system root access granted");
    break; // Break prevents unintended fall-through!
  case "editor":
    console.log("Edit access granted");
    break;
  default:
    console.log("Standard view access");
}

2.2 Loops (for, while, for...of, for...in)

Loops automate repeated execution. Modern JavaScript offers specialized iteration statements depending on whether you are working with indices, collection values, or object keys.

Figure 2.2: Comparison of JavaScript Loop Execution Mechanics Standard for Loop Index-based numeric counter for (let i=0; i<n; i++) Fixed iterations & steps for...of Loop (ES6) Iterates over VALUES for (const val of arr) Arrays, Maps, Sets, Strings for...in Loop Iterates over KEYS for (const key in obj) Object properties inspection

Figure 2.2: Loop mechanics comparison. Use for...of to inspect elements/values of collections, and for...in to inspect object property keys.

2.3 Hoisting

Hoisting is JavaScript's default behavior of scanning declarations during the creation phase of an Execution Context and registering variable and function identifiers in memory before any code actually runs.

Figure 2.3: Hoisting Execution Mechanics — var vs let/const in the Engine // What You Write console.log(x); // undefined var x = 5; Hoisting var x; // Hoisted & initialized to undefined console.log(x); // Prints undefined x = 5; // Assignment stays in place Temporal Dead Zone (TDZ) for let & const: let and const are also hoisted, but NOT initialized with a value. Accessing them before their declaration line throws a ReferenceError.

Figure 2.3: Hoisting lifts variable declarations to memory before code execution. var is initialized to undefined, while let/const reside in the Temporal Dead Zone.

MODULE COMPREHENSIVE QUIZ

Module 2 Final Quiz

Test your understanding across all 3 topics of this module with interview-grade questions, tricky edge cases, and code output predictions.

Take Module 2 Final Quiz →
Yukti Mascot