JavaScript var
Example
Create a variable called carName and assign the value "Volvo" to it:
More examples below.
Description
The var
statement declares a variable.
Variables are containers for storing information.
Creating a variable in JavaScript is called "declaring" a variable:
After the declaration, the variable is empty (it has no value).
To assign a value to the variable, use the equal sign:
You can also assign a value to the variable when you declare it:
Note
A variable declared without a value have the value undefined
.
See Also:
JavaScript Reference: JavaScript let
JavaScript Reference: JavaScript const
Tutorials
JavaScript Tutorial: JavaScript Variables
JavaScript Tutorial: JavaScript Let
JavaScript Tutorial: JavaScript Const
JavaScript Tutorial: JavaScript Scope
Syntax
Parameters
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
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 y = 6;
document.getElementById("demo").innerHTML = x + y;
Use let to assign 5 to x and 6 to y, and display x + y:
let y = 6;
document.getElementById("demo").innerHTML = x + y;
Declare many variables in one statement.
Start the statement with var and separate the variables by comma:
age = 30,
job = "carpenter";
Declare many variables in one statement.
Start the statement with let and separate the variables by comma:
age = 30,
job = "carpenter";
Using var in a loop:
for (var i = 0; i < 5; i++) {
text += i + "<br>";
}
Using let in a loop:
for (let i = 0; i < 5; i++) {
text += i + "<br>";
}
Browser Support
var
is an ECMAScript1 (JavaScript 1997) feature.
It is supported in all browsers:
Chrome | Edge | Firefox | Safari | Opera | IE |
Yes | Yes | Yes | Yes | Yes | Yes |