JS: var/function Order

By Xah Lee. Date: . Last updated: .

in JavaScript, variable declared with var is automatically moved to the top.

This is called name hoisting. This applies to both variable name and function name.

When inside a function definition:

Assignment Order is Never Changed

Assignment order is never changed. That is, JavaScript may see a variable earlier than in the source code, but the variable's value is still undefined until the assignment line in source code is reached.

Examples

// example showing name hoisting for function name

console.log(f()); // prints 7

function f () { return 7; }
// example showing name hoisting

console.log(n);   // prints “undefined”

var n; // un-initiated var has value “undefined”

// accessing undeclared and un-assigned var is a reference error
console.log(x);   // ReferenceError: x is not defined

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 the top of function body

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();

// prints
// undefined
// 1
// 2
// 3

above is equivalent to:

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

f();

Assignment Order Does Not Change

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;

「let」 and 「const」 Declaration

let and const declaration does not have name hoisting. This is simple and intuitive.

[see JS: let Declaration]

[see JS: const Declaration]

JavaScript Variable Topic

  1. JS: Variable
  2. JS: var/function Order
  3. JS: var Name Scope
  4. JS: let Declaration
  5. JS: const Declaration

Function Topic

  1. JS: Define Function
  2. JS: Arrow Function
  3. JS: Function Parameters
  4. JS: var/function Order
  5. JS: var Name Scope
  6. JS: Function Declaration vs Function Expression
  7. JS: Closure
  8. JS: Functional Programing
  9. JS: Function Call, Apply, Bind
  10. JS: Function Argument Default Value
  11. JS: Function Rest Parameters
  12. JS: Function Argument Destructure

  1. JS: Function Object
  2. JS: Function.prototype
Liket it? Put $1 at patreon.

Or, Buy JavaScript in Depth