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.


// 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++) {


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

above is equivalent to:

function f ()  {
    var i;
    for (i = 1; i <= 3; i++) {


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:

var x = 5;

is equivalent to:

var 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: Function Parameters
  3. JS: var/function Order
  4. JS: var Name Scope
  5. JS: Function Declaration vs Function Expression
  6. JS: Closure
  7. JS: Functional Programing
  8. JS: Function Call, Apply, Bind
  9. JS: Function Argument Default Value
  10. JS: Function Rest Parameters
  11. JS: Arrow Function

  1. JS: Function Object
  2. JS: Function.prototype
Like what you read? Buy JavaScript in Depth