What are The major differences between "const" and "let"?

Sometimes when declaring a variable, the const keyword is used and at other times, the let keyword is used. What are the major differences between the both of them and when should either of them be used in declaring a variable?

https://www.codecademy.com/paths/web-development/tracks/getting-started-with-javascript/modules/learn-javascript-functions/lessons/functions/exercises/return

When a variable is created with the let keyword, it is truly a variable and can be reassigned:

let n = 5 //n equals 5
n = 6     //now n is equal to 6

On the other hand, a variable created with the const keyword, is a constant and can not be changed:

const m = 5  //m equals 5
m = 6        //This will result in an error as you can not change
             //the value of a constant.

let should be used to hold a value you are expecting to change, such as the number of players in a gaming server.
On the other hand const offers more security and should be used for storing something like a permanent password, that you don’t want changed.

5 Likes

let is also useful for scoping variables, as we can use it to temporarily re-define a variable with block scope without affecting another variable of the same name that already exists outside of the block:

let aNumber = 42;
console.log(`The number is ${aNumber}`);


for (let i = 0; i < 5; i++) {
    let aNumber = 10 ** i;
    console.log(`The number is now ${aNumber}`);
}

console.log(`The number is now ${aNumber}`);

This produces the following output:

The number is 42
The number is now 1
The number is now 10
The number is now 100
The number is now 1000
The number is now 10000
The number is now 42
2 Likes

In addition to both of the above answers, once you get to arrow functions, it’s good to declare functions with the const because they’re not something you generally want overwritten, so it adds a bit of protection later on in the code.

3 Likes

All great insights. Thank you all.

1 Like