Difference between let and const in Javascript
There are 3 different keywords used to declare a variable in JavaScript. They are var
, let
, and const
. We have already discussed the difference between let and var. Here we will discuss the difference between let and const.
Let and const are the two new keywords introduced in ES6. They both are used to declare variables in JavaScript. But they have different scopes and behavior.
Let's see each of them one by one and then explore the differences.
The Basics of let and const
let and const are both used to declare variables in JavaScript, but they are used in slightly different ways.
Variables declared with let
keyword can be reassigned, while any variable declared as const
can't be reassigned. It will cause an error.
For example, if you declare a variable with let
, you can change its value later in the code:
Example
let count = 0;
count = 1;
console.log(count); // Output: 1
On the other hand, if you declare a variable with const
, you cannot change its value later in the code:
Example
const count = 0;
count = 1; // Error: Assignment to constant variable
console.log(count);
Difference between let and const
The main difference between let
and const
is that let
variables can be reassigned while const
variables cannot be reassigned.
Also, there are a few minor differences between them at different levels.
Let's see them one by one.
Scope
Both let and const have block level scope. Means that they are only accessible within the block in which they are declared. A block is a section of code contained within curly braces {}.
For example, if you declare a variable with let
inside a block, it will only be accessible within that block:
Example
{
let message = "Hello";
console.log(message); // Output: Hello
}
console.log(message); // Error: message is not defined
The same is true for const
:
Example
{
const message = "Hello";
console.log(message); // Output: Hello
}
console.log(message); // Error: message is not defined
However, if you declare a variable with let
or const
outside of a block, it will be accessible within the entire function in which it is declared.
Use Cases
Now that we have seen the basics of let
and const
, let's see when to use them.
-
let is used to declare variables that will be reassigned later in the code.
let count = 0; count = 1; // Valid
-
const variables are read-only and cannot be reassigned.
const pi = 3.14; pi = 3; // Invalid
-
let is used in for loops to declare loop variables that are scoped to the loop block. For example:
for (let i = 0; i < 10; i++) { console.log(i); // Output: 0, 1, 2, ..., 9 } console.log(i); // ReferenceError: i is not defined
-
Const is used to define those variables whose values are going to stay constant throughout the program.
const PI = 3.14; const GRAVITY = 9.8;
Overall, let and const are useful for declaring block level variables. In which const can't be reassigned once declared but let can be reassigned.