4 ways to Declare a Javascript Variable:
- using
var
- using
let
- using
const
- using
nothing
What are Variables?
Variable are container for storing data
example:
var x = 5;
var y = 6;
var z = x + y;
When to Use JavaScript var?
Always declare Javascript variables with var
,let
or const
.
the var
keyword is used in all JavaScript code from 1995 to 2015.
the let
and const
keywords were added to JavaScript in 2015.
if you want your code to run in older browser, you must use var
.
When to Use JavaScript const?
if you want a general rules: always declare variables with const
.
if you think the value of the variable can change, use let
.
in this example, price1
,price2
, anda total
, are variables:
const price1 = 10;
const price2 = 20;
let total = price1 + price2; //30
noted: the two variables price1
and price2
are declared with the const
keyword. there are constant values and cannot changed. the variable total
is declared with the let
keyword.
JavaScript Identifiers
All JavaScript variables mus be identified with unique names.
The general rules for constructing names for variables are:
- Names can contain letters, digits, underscores, and dollar signs.
- Names must begin with a letters.
- Names can also begin with $ and _.
- names are case sensitive(a and A different variables).
- reserved words cannot be used as names.
The Assignment operator
In JavaScript, the equal sign(=
) is an assigment operator, not an equal to
operator.
s = s + 16
Declaring a JavaScript Variable
You can declare a JavaScript variable with the var
or the let
keyword:
var carName;
or
let carName;
One Statement, Many Variables
let name='aji', lastName='dk',address:'Indonesia'
Value = undefined
A variable declared without a value will have the value undefined.
Top comments (0)