JS: var Declaration

By Xah Lee. Date: . Last updated: .

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

Var Declaration

var name; → declares a variable.

// declare variable
var x;
var y;

Multiple variables can be declared on the same line, separated by comma.

For example, var name1, name2, name3 …;

// declare multiple variables
var a, b, c;

Multiple variables can be declared and assigned at the same time.

// declare variable and assign
var x = 4;
// declare variable and assign multiple variables
var a = 1, b = 2, c = 3;
// declare multiple variables, some with value
var a, b = 2, c;

// all true
console.log(a === undefined);
console.log(b === 2);
console.log(c === undefined);

When a variable is declared but not assigned, the default value is undefined:

var x;
console.log(x === undefined); // true

When a variable is not declared nor assigned, and you try to access it, you get ReferenceError.

var x;
console.log(x === undefined); // true

// ReferenceError: y is not defined
console.log(y);

You should ALWAYS declare variables. It is harmless if you declared a variable redundantly multiple times.

var x;
console.log(x === undefined); // true
var x;
console.log(x === undefined); // true

var y = 3;
console.log(y === 3); // true
var y;
console.log(y === 3); // true

Variable Assignment

Variable assignment returns a value.

// variable assignment returns a value
var xx;
console.log(xx = 3);            // 3

So, variable assignment can be chained.

var xx;
var yy;

console.log(xx = yy = 3); // 3
console.log(xx === 3);    // true
console.log(yy === 3);    // true

var Declaration Order

JS: var Declaration Order

var Name Scope

JS: var Name Scope

JS Variable

  1. Value Types
  2. let
  3. const
  4. var
  5. var Order
  6. var Scope
  7. Global Variable
  8. Destructuring Assignment
Like it? Help me by telling your friends. Or, Put $5 at patreon.

Or, Buy JavaScript in Depth

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

Web Dev Tutorials