JavaScript: var Declaration

By Xah Lee. Date: . Last updated: .

Note: var deprecated

Note: 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.

Var Declaration

var name;
declare a variable.
// declare variable
var x;
var y;
var name1, name2, name3 etc;
declare multiple variables.
// declare multiple variables
var a, b, c;
var name = val;
declare and assign.
var name1 = val1, name2 = val2, name3 = val3 etc;
declare and assign multiple variables
// declare variable and assign
var x = 4;
// declare variable and assign multiple variables
var a = 1, b = 2, c = 3;
var name_or_assign_1, name_or_assign_2 etc;
declare variables, some with assignment.
// 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);

var with no value

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

Same var declared multiple times

It is harmless if you declared a variable redundantly multiple times.

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

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

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);
console.log(yy === 3);

var Declaration Order

var Name Scope

JavaScript variable

JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types




Object and Inheritance




Iterable 🌟