Learn how the Memory Creation Phase enables accessing function declarations and variables before their line of creation.
Learn how variables act as labeled containers for data using const, let, and var to manage lexical scope and reassignment safely in modern applications.
Hoisting is JavaScript's default engine behavior of allocating memory space for variable and function declarations during Phase 1 (Memory Creation) before running Phase 2 (Code Execution).
Because memory is created before execution starts, function declarations can be safely invoked before their line of appearance in the source code!
var Variables: Initialized with undefined during Phase 1. Accessing a var variable before its assignment line returns undefined (not a crash!).let and const: Memory is allocated during Phase 1, but they remain uninitialized in the Temporal Dead Zone (TDZ). Accessing them before initialization throws a ReferenceError!// Function hoisting (Works!)
sayHello(); // Output: "Hello World!"
function sayHello() {
console.log("Hello World!");
}
// Var hoisting (Returns undefined)
console.log(userAge); // Output: undefined
var userAge = 25;
// Let hoisting (Throws ReferenceError!)
// console.log(userName); // ReferenceError: Cannot access 'userName' before initialization
let userName = "Alex";
Function expressions assigned to variables (var greet = function() {}) hoist as variables, NOT as functions! Calling greet() before assignment throws TypeError: greet is not a function.
// Uncaught TypeError: greet is not a function
// (because 'greet' is currently 'undefined' during execution line 1!)
greet();
var greet = function() {
console.log("Hi!");
};
const or let reside in the TDZ and cannot be called before their declaration line.var Hoisting: Relying on var hoisting creates confusing code where variables are read before assignment. Declare variables at the top of their block.Use modern arrow functions or declare functions clearly before invocation. Next, let's explore concise ES6 Arrow Functions!