Variables
There are two ways to declare a variable in javascript, using const
and let
.
let
let word = "JavaScript";
console.log(word); // JavaScript
The above example shows how to declare a variable using let.
Variable declared using let
can be re-assigned later.
let word = "JavaScript";
word = "HTML"; // variable word is re-assigned with "HTML"
let
is used to create a variable whose value changes in the code.
const
const word = "JavaScript";
console.log(word); // JavaScript
word = "HTML"; // ❌ Type error: this will break script
Variables defined with const
cannot be re-assigned.
let vs const
How do you choose whether to use let
or const
? Const is always preferable until you realise you need to be able to re-assign the variable later on, at which point you should switch to let
.
For example, if you define a variable count
(which you expect to increment), you will immediately recognise it and use let
.
The advantage of using const
is that once a variable is declared as an array, it will remain an array indefinitely (but as you will see later on, the elements inside the array might change). Because you know the variable will always be of type array, you can confidently use array methods on it.
Even though var still works, its use is discouraged because it can be confusing in a variety of situations. As a result, you can simply replace var with let (or const if the variable is not being reassigned).
When defining variables, avoid the use of var. Use let or const instead.