Declaring variables in JS
There are three different ways of declaring variables in JavaScript:
let,
const and var. Let and
const were introduced in ES6, so they are quite new and modern
in JS. On the
other hand var is the older way of declaring variables.
let
We use let keyword to declare a
variable which can by modified later,
during the execution of a program.
let price = 100;
price = 150;
In technical terms we call this reassigning a value to a variable. We can also say that we mutate a
variable. If there is a need to mutate the variable, it’s the perfect case for using let. Another
one
is when we want to declare an empty variable.
const
On the other hand, we can use const
keyword to declare variables that
are not supposed to be changed at any point in the future. So the value in a const variable cannot
be changed.
const productionYear = 1997;
So if we try to reassign it, it won’t work.
And that’s how the const keyword does; it creates a variable that we cannot reassign or in technical
terms, we create an immutable variable (the one that can’t be mutated). It also means that it’s
impossible to declare empty const variables.
So an often advice presented ad a best practice for writing clean code is to use const by default
and let only when we are sure or convinced that a variable needs to be changed at some point in the
future.
It’s for the reason that it’s a sensible approach to have as little variable mutations or changes as
possible because they can introduce a bigger potential to create bugs.
var
There’s also a third way of declaring variables - with the usage of
var
keyword.
var lenght = 300;
But it’ the older one.