JavaScript Variables
Variables are Containers for Storing Data
JavaScript Variables can be declared in 4 ways:
Automatically
Using var
Using let
Using const
Example of Automatically:
x=10;
y=20;
z=x+y;
[Link](z);
output:
Variable Declaration using var
var x=10;
var y=20;
var z=x+y;
[Link]("sum is:",z);
Output
Variable Declaration using let
let x=10;
let y=20;
let z=x+y;
[Link]("sum is:",z);
output:
The var keyword was used in all JavaScript code from 1995 to 2015.
The let and const keywords were added to JavaScript in 2015.
The var keyword should only be used in code written for older browsers.
Variable declaration using const
const x=10;
x=x+2;
[Link](x);
var x=10;
[Link]("Outside block:"+x);
{
let x=100;
[Link]("inside block:"+x);
}
[Link](x);
output:
JavaScript Identifiers
All JavaScript variables must be identified with unique names.
These unique names are called identifiers. JavaScript identifiers are case-
sensitive.
Identifiers can be short names (like x and y) or more descriptive names
(age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers)
are:
Names can contain letters, digits, underscores, and dollar signs.
Names must begin with a letter.
Names can also begin with $ and _ (but we will not use it in this
tutorial).
Names are case sensitive (y and Y are different variables).
Reserved words (like JavaScript keywords) cannot be used as names.