JavaScript: Variable & Function Declaration Order: Name Hoisting

, , …,

in JavaScript, variable declaration is automatically moved to the top. This is called name hoisting. This applies to both variable name and function name.

// example showing name hoisting for function name
console.log(f());               // prints 7
function f () { return 7; };    // function can be placed at bottom
// example showing name hoisting for variable name
console.log(x);   // ReferenceError: x is not defined
console.log(n);   // prints undefined
var n; // un-initialized var by default has value 「undefined」

Name hoisting applies inside a function definition too.

// example showing variable name hoisting, inside a function definition

var n = 3;

function f ()  {
    return n;
    var n;
};

console.log(f());       // prints undefined.
// Because, the “var n” inside the function is moved to top

Here's another example. A typical loop inside a function:

function f ()  {
    // console.log(x); // ReferenceError: x is not defined
    // console.log(i); // undefined.
    for (var i = 1; i <= 3; i++) {
        console.log(i);
    }
}

f();

above is equivalent to:

function f ()  {
    var i;
    for (i = 1; i <= 3; i++) {
        console.log(i);
    }
}

f();

Assignment Order Matters

Name hoisting moves the name to the top, but it does not move the assignment with it.

// example showing that assignment order matters. Name hoisting is about name only, not assignment

console.log(x);  // prints undefined
var x = 5;

The following:

console.log(x);
var x = 5;

is equivalent to:

var x;
console.log(x);
x = 5;

Variable Scope: Function Level vs Block Level

JavaScript Variable Scope: Function Level vs Block Level

blog comments powered by Disqus