JavaScript var Statement

JavaScript var

Example

Create a variable called carName and assign the value “Volvo” to it:

var carName = “Volvo”;

Try it Yourself »

More examples below.

Definition and Usage

The var statement declares a variable.

Variables are containers for storing information.

Creating a variable in JavaScript is called “declaring” a variable:

var carName;

After the declaration, the variable is empty (it has no value).

To assign a value to the variable, use the equal sign:

carName = “Volvo”;

You can also assign a value to the variable when you declare it:

var carName = “Volvo”;

Syntax

var name = value;

Parameters

Parameter
Description

name
Required.
The name of the variable.
Variable names must follow these rules:

Must begin with a letter, or $, or _
Names are case sensitive (y and Y are different)
Reserved JavaScript words cannot be used as names

value
Optional.
A value to be assigned to the variable.

Note

ECMAScript6 (ES6 / JavaScript 2015) encourage you to declare variables with let not var.

More Examples

Use var to assign 5 to x and 6 to y, and display x + y:

var x = 5;
var y = 6;
document.getElementById(“demo”).innerHTML = x + y;

Try it Yourself »

Use let to assign 5 to x and 6 to y, and display x + y:

let x = 5;
let y = 6;
document.getElementById(“demo”).innerHTML = x + y;

Try it Yourself »

Declare many variables in one statement.

Start the statement with var and separate the variables by comma:

var lastName = “Doe”,
age = 30,
job = “carpenter”;

Try it Yourself »

Declare many variables in one statement.

Start the statement with let and separate the variables by comma:

let lastName = “Doe”,
age = 30,
job = “carpenter”;

Try it Yourself »

Using var in a loop:

let text = “”;
for (var i = 0; i < 5; i++) {
  text += i + “<br>”;
}

Try it Yourself »

Using let in a loop:

let text = “”;
for (let i = 0; i < 5; i++) {
  text += i + “<br>”;
}

Try it Yourself »

Browser Support

var is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome
IE
Edge
Firefox
Safari
Opera

Yes
Yes
Yes
Yes
Yes
Yes