JavaScript has 4 ways of defining variables:
General rules for variables:
- Always define variables
- Always use
constif the value should not change - Always use
constif the type should not be changed (Arrays or Objects) - Use
letonly if you can’t useconst - Use
varonly if you must support old browsers
Automatically
The variable will be defined on first use
x = 5;
y = 6;
// x and y are now 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;
letandconstwere added in 2015,varshould 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;