JS: var Declaration Order

By Xah Lee. Date: . Last updated: .

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

This is called name hoisting.

For example, the following:

var x = 5;

is equivalent to:

var x;
x = 5;

Here's 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 n = 3;

function f ()  {
    return n;
    var n;

console.log(f() === undefined); // true
// 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); // print “undefined”, but this is not an error

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


JS Variable Topic

  1. JS: let Declaration
  2. JS: const Declaration
  3. JS: var Declaration
  4. JS: var Declaration Order
  5. JS: var Name Scope
  6. JS: Global Variable
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

If you have a question, put $5 at patreon and message me.

Web Dev Tutorials

  1. HTML
  2. Visual CSS
  3. JS Basics
  4. JS in Depth
  5. JS Reference
  6. DOM
  7. SVG
  8. JS Misc