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.

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.