/ˈvɛəriəbl ˈhoʊstɪŋ/

noun … “Declarations move to the top of their scope.”

Variable Hoisting is a behavior in certain programming languages, such as JavaScript, where variable and function declarations are conceptually moved to the top of their containing scope during compilation or interpretation. Hoisting affects accessibility and initialization timing, often causing variables declared with var to be available before their explicit declaration line, while let and const remain block-scoped and uninitialized until the declaration line, creating a temporal dead zone.

Key characteristics of Variable Hoisting include:

  • Declaration hoisting: only the declaration itself is moved; initialization remains in place.
  • Function hoisting: entire function definitions can be hoisted, allowing calls before their declaration in the code.
  • Temporal dead zone: variables declared with let or const cannot be accessed before their declaration, preventing undefined behavior.
  • Scope-dependent: hoisting occurs differently depending on global scope or block scope.
  • Predictability: understanding hoisting helps prevent bugs related to variable access before initialization.

Workflow example: In JavaScript:

console.log(a)  -- Output: undefined
var a = 10

function hoistExample() {
    console.log(b)  -- Output: ReferenceError
    let b = 20
}

hoistExample()

Here, a is hoisted and initialized to undefined, while b is in a temporal dead zone, resulting in a ReferenceError if accessed before its declaration.

Conceptually, Variable Hoisting is like unpacking boxes at the top of a shelf: the space (declaration) exists from the beginning, but the items inside (initialization) aren’t available until you open the box at the right time.

See Scope, Global Scope, Block Scope, Closure, Lexical Scoping.