JS: var Declaration Order (Name Hoisting)

By Xah Lee. Date: . Last updated: .

var deprecated

πŸ›‘ WARNING: The use of var is deprecated since ES2015, due to its name hoisting complexity and name scope complexity [see var Name Scope] , you should never use var. Use let Declaration instead.

Name Hoisting

Variable declared with var has a behavior that is effectively equivalent to as if the declaration is moved to the top of the function block the var appears in, or top of source code file.

This is called name hoisting.

For example, the following:

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

is equivalent to:

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

Here is a example showing the effect of name hoisting:

// example showing name hoisting

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

// but accessing variable that's declared later is ok
console.log( (n === undefined) === true );

var n; // un-initiated var has value β€œundefined”

No Change to Assignment Order

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 === undefined); // true
var x = 5;

var Name Hoisting Inside Function

Name hoisting applies inside a function body too.

Inside a function body, var declaration is moved to the top in the function block.

/*
example showing variable name hoisting, inside a function body
*/

var xx = 3;

function ff() {
  return xx;
  var xx;
}

console.log((ff() === undefined) === true);

/*
Because, the β€œvar xx” inside the function is moved to the top of function body
*/

Here is another example. A typical loop inside a function:

/*
example showing variable name hoisting, inside a function body, with loop
*/

function ff() {

  console.log(i);
  // print β€œundefined”, but this is not an error

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

ff();

/*
prints

undefined
1
2
3
*/

Above is equivalent to:

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

f();

JavaScript, keyword var

JavaScript, Function Declaration vs Function Expression

BUY Ξ£JS JavaScript in Depth