JavaScript var Statement

Definition and Usage

The 'var' statement declares a variable.

Variables are containers for storing information.

Creating a variable in JavaScript is called 'variable declaration':

var carName;

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

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

carName = "Volvo";

You can also assign a value to a variable when declaring it:

var carName = "Volvo";

For more information about variables, please learn our JavaScript Variables tutorial and JavaScript Scope tutorial.

Example

Create a variable named carName and assign it the value "Volvo":

var carName = "Volvo";

Try It Yourself

More TIY examples are at the bottom of the page.

Syntax

var varname = value;

Parameter Value

Parameter Description
varname

Required. Specify the name of the variable.

Variable names can contain letters, numbers, underscores, and dollar signs.

  • Variable names must start with a letter
  • Variable names can also start with $ and _
  • Variable names are case-sensitive (y and Y are different variables)
  • Reserved words (such as JavaScript keywords) cannot be used as variable names
value

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

Comment:Variables that are not assigned a value at the time of declaration will have an 'undefined' value.

Technical Details

JavaScript Version: ECMAScript 1

More Examples

Example

Create two variables. Assign the number 5 to x, and the number 6 to y. Then display the result of x + y:

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

Try It Yourself

Example

You can declare multiple variables in a single statement.

Start statements with 'var' and separate variables with commas:

var lastName = "Gates",
age = 19,
job = "carpenter";

Try It Yourself

Example

In the loop, use the variable:

var text = "";
var i;
for (i = 0; i < 5; i++) {
  text += "The number is " + i + "<br>";
}

Try It Yourself

Browser Support

Statement Chrome IE Firefox Safari Opera
var Support Support Support Support Support

Related Pages

JavaScript Tutorial:JavaScript Variable

JavaScript Tutorial:JavaScript Scope