HTML tutorial
CSS3 tutorial
Bootstrap tutorial
JavaScript tutorial
JQuery tutorial
AngularJS tutorial
React tutorial
NodeJS tutorial
PHP tutorial
Python tutorial
Python3 tutorial
Django tutorial
Linux tutorial
Docker tutorial
Ruby tutorial
Java tutorial
C tutorial
C ++ tutorial
Perl tutorial
JSP tutorial
Lua tutorial
Scala tutorial
Go tutorial
ASP.NET tutorial
C # tutorial
Create a variable called carName and assign the value "Volvo" to it
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:
A variable declared without a value have the value undefined
.
JavaScript Reference: JavaScript let
JavaScript Reference: JavaScript const
JavaScript Tutorial: JavaScript Variables
JavaScript Tutorial: JavaScript Let
JavaScript Tutorial: JavaScript Const
JavaScript Tutorial: JavaScript Scope
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. |
ECMAScript6 (ES6 / JavaScript 2015) encourage you to declare variables with let not var.
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;
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;
Declare many variables in one statement.
Start the statement with var and separate the variables by comma:
var lastName = "Doe",
age = 30,
job = "carpenter";
Declare many variables in one statement.
Start the statement with let and separate the variables by comma:
let lastName = "Doe",
age = 30,
job = "carpenter";
Using var in a loop:
let text = "";
for (var i = 0; i < 5; i++) {
text += i + "<br>";
}
Using let in a loop:
let text = "";
for (let i = 0; i < 5; i++) {
text += i + "<br>";
}
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 |