What's the difference between var, let and const keywords?
Variables declared with var
keyword are function scoped.
What this means that variables can be accessed across that function even if we declare that variable inside a block.
function giveMeX(showX) {
if (showX) {
var x = 5;
}
return x;
}
console.log(giveMeX(false));
console.log(giveMeX(true));
The first console.log
statement logs undefined
and the second 5
. We can access the x
variable due
to the reason that it gets hoisted at the top of the function scope. So our function code is intepreted like this.
function giveMeX(showX) {
var x; // has a default value of undefined
if (showX) {
x = 5;
}
return x;
}
If you are wondering why it logs undefined
in the first console.log
statement remember variables declared without an initial value has a default value of undefined
.
Variables declared with let
and const
keyword are block scoped. What this means that variable can only be accessed on that block {}
on where we declare it.
function giveMeX(showX) {
if (showX) {
let x = 5;
}
return x;
}
function giveMeY(showY) {
if (showY) {
let y = 5;
}
return y;
}
If we call this functions with an argument of false
it throws a Reference Error
because we can't access the x
and y
variables outside that block and those variables are not hoisted.
There is also a difference between let
and const
we can assign new values using let
but we can't in const
but const
are mutable meaning. What this means is if the value that we assign to a const
is an object we can change the values of those properties but can't reassign a new value to that variable.