JavaScript var Statement
- Previous Page try...catch
- Next Page while
- Go Back to the Previous Level JavaScript Statement Reference Manual
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";
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.
|
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;
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";
Example
In the loop, use the variable:
var text = ""; var i; for (i = 0; i < 5; i++) { text += "The number is " + i + "<br>"; }
Browser Support
Statement | Chrome | IE | Firefox | Safari | Opera |
---|---|---|---|---|---|
var | Support | Support | Support | Support | Support |
- Previous Page try...catch
- Next Page while
- Go Back to the Previous Level JavaScript Statement Reference Manual