Quick Overview
Hoisting moves no code anywhere. Memory is reserved during the first phase, so a `function` declaration is fully available early while a `var` merely exists holding `undefined` until its assignment runs.
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.Write it yourself. The tests below run against your code.
Use modern arrow functions or declare functions clearly before invocation. Next, let's explore concise ES6 Arrow Functions!
Primitives copy by value and objects copy by reference, so `b = a` duplicates a number but shares an object. That single distinction explains most surprise mutations in a codebase.
`const` prevents reassignment, not mutation: a `const` object's properties can still be changed. `let` is scoped to its block, while `var` is function-scoped and leaks out of loops.
Only backticks interpolate: `${user}` reads the variable, while the identical text in quotes prints literally. Strings are immutable, so every method returns a new one rather than editing in place.