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

var Declaration Order

var Name Scope

var Name Scope

Buy JavaScript in Depth

JavaScript in Depth

JS Obj Ref

DOM


JavaScript in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Regular Expression

Date

Set Object

Map Object

Number

Misc