JavaScript Hoisting Explained

Hoisting is a concept in JavaScript that allows variable and function names to be used before they are declared. This happens because JavaScript moves declarations to the top during compilation.

Variable Hoisting Example

    x = 1;
    alert('x = ' + x); // Output: x = 1
    var x;

Hoisting with Multiple Variables

    x = 1;
    y = x;
    alert('x = ' + x); // Output: x = 1
    alert('y = ' + y); // Output: y = 1
    var x;
    var y;

Hoisting Does Not Apply to Initialized Variables

    alert('x = ' + x); // Output: x = undefined
    var x = 1;

Function Hoisting Example

    alert(Sum(5, 5)); // Output: 10
    function Sum(val1, val2) {
    return val1 + val2;
    }

Function Expression Hoisting (Not Hoisted)

    Add(5, 5); // Error: Add is not defined
    var Add = function (val1, val2) {
    return val1 + val2;
    };

Another Example: Hoisting Order (Functions Before Variables)

    alert(UseMe); // Output: function UseMe()
    var UseMe;
    function UseMe() {
    alert("UseMe function called");
    }

Key Concepts

  • JavaScript hoists declarations (variables & functions) to the top of their scope.
  • Only declarations move—initializations do not.
  • Function declarations are fully hoisted, but function expressions are not.
  • Function definitions are prioritized before variable declarations.