The var vs. let vs. const
Let's compare the var, let, and const keywords in JavaScript!
We'll cover the following
The const
Keyword #
const
is block-scoped. This means that the variable declared with const cannot be redeclared or reassigned.
//code will throw an errorconst pi=3.14console.log(pi)pi=3;
The code above will generate an error as we cannot assign a new value to the variable pi
as we have declared it using const
.
//code will throw an errorconst num=5;const num=6;
The code above will also generate an error as we cannot redeclare variables using const
.
The var
Keyword #
Variables declared with var
are function-scoped. This means that if a variable is declared anywhere else besides a function using var
, it will always exist in the global scope.
Variable declared using var
can be redeclared as well.
function foo(){var n=6;console.log(n);}var n=5;console.log(n);foo();
The values of n
inside the function and outside the function are different according to their respective scopes.
The value of n
outside the function scope remains the same regardless of what the value of n
is inside the function scope.
Also, as stated, variables can be redeclared using
var
:
var myVar=10;console.log(myVar)var myVar=15;console.log(myVar)
The let
Keyword #
The ES6 introduced the let
keyword, which lets you define variables that are block-scoped.
As with variables declared with const
, the variables declared with let
cannot be redeclared.
//code will throw an errorfunction foo(n) {if (n == 6) {let num = 2;}console.log(num);}var n = 6;console.log(n);foo(6);
The above code has thrown an error because we initialized the num
variable in the if-statement block. As it has been declared using let
, we cannot access it outside the if block.
This code will work fine if we use var
as they are function-scoped and can be accessed throughout the function.
function foo(n) {if (n === 6) {var num = 2;}console.log(num);}var n = 6;console.log(n);foo(n);
Let’s look at another example of scoping using loops:
//code will throw an errorfor(var i=0;i<3;i++){console.log(i)}console.log("i outside the loop: ", i);for(let j=0;j<3;j++){console.log(j);}console.log("j oustide the loop :", j);
In the above code, i
is declared using var
can be accessed outside the loop block. However, j
declared using let
cannot be accessed outside the block scope, and hence, the above code generates an error.
Furthermore, the let
statement does not let you redeclare any variable.
The code below will throw an error:
//code will throw an errorlet a=2;let a=3;
Finally, variable declaration using let
, const
, or var
depends on what scope you want. We’ll now move on to the challenges.