JavaScript has 4 ways of defining variables:
General information on variables:
- Always define variables
- Always use
const
if the value should not change - Always use
const
if the type should not be changed (Arrays or Objects) - Use
let
only if you can’t useconst
- Use
var
only if you must support old browser
Automatically
The variable will be defined on first use
x = 5;
y = 6;
// x and y now are defined
z = x + y;
It is considered good programming practice to define the variable before use
Var
The var
keyword was added to JavaScript from 1995 to 2015
var x = 5;
var y = 6;
// x and y are already defined
var z = x + y;
let
andconst
were added in 2015,var
should be only used when a old browser is used.
Let
let x = 5;
let y = 6;
let z = x + y;
Const
The const
is used to define a constant variable, one who’s value doesn’t change once defined.
const x = 5;
const y = 6;
const z = x + y;
Let or Const
It’s prefered to use const
for only constant variables (those that won’t be changed), and let
for all other variables.
// Pi never changes, so it's a constant
const pi = 3.14;
// x could change
let x = 5;