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

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

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

JavaScript in Depth

JS Obj Ref


JavaScript in Depth

Basic Syntax

Value Types




Object Property

Object and Inheritance



Iterable 🌟

Regular Expression


Set Object

Map Object