< JavaScript Statements Reference
Example
Create a variable called carName and assign the value "Volvo" to it:
var carName = "Volvo";
Try it Yourself »
More "Try it Yourself" 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";
For more information about variables, read our JavaScript Variables Tutorial and JavaScript Scope Tutorial.
Browser Support
Statement | |||||
---|---|---|---|---|---|
var | Yes | Yes | Yes | Yes | Yes |
Syntax
var varname = value;
Parameter Values
Parameter | Description |
---|---|
varname | Required. Specifies the name of the variable. Variable names can contain letters, digits, underscores, and dollar signs.
|
value | Optional. Specifies the value to assign to the variable. Note: A variable declared without a value will have the value undefined |
Technical Details
JavaScript Version: | 1.0 |
---|
More Examples
Example
Create two variables. Assign the number 5 to x, and 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 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 »
Example
Using variables in loops:
var text = "";
var i;
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
Try it Yourself »
Related Pages
JavaScript Tutorial: JavaScript Variables
JavaScript Tutorial: JavaScript Scope
< JavaScript Statements Reference