JavaScript: 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 var Name Scope] , you should never use var. Use let instead. [see let Declaration]

Var Declaration

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

var Declaration Order

var Name Scope

var Name Scope

JavaScript variable

JavaScript in Depth

JavaScript in Depth

Basic Syntax

Value Types





Object and Inheritance



Iterable 🌟