142k views
5 votes
What is the difference between const and let javascript?

User Infroz
by
7.2k points

1 Answer

1 vote

Final answer:

The main difference between const and let in JavaScript is their scope and mutability. The const keyword is used to declare variables that are constant and cannot be reassigned, while the let keyword is used to declare variables that can be reassigned and have block scope.

Step-by-step explanation:

const and let are both keywords used in JavaScript for declaring variables. The main difference between them lies in their scope and mutability.

const, short for constant, is used to declare variables that are meant to be constant and cannot be reassigned a new value once it has been declared. This means that the value of a const variable remains the same throughout the program.

On the other hand, let is used to declare variables that are block-scoped and can be reassigned. This means that the value of a let variable can be changed within the block it is defined.

For example:

const pi = 3.14;
pi = 3.14159; //Error: Cannot assign to const variable

let x = 5;
if (true) {
let x = 10;
console.log(x); //Output: 10
}
console.log(x); //Output: 5

In the above code snippet, the const variable 'pi' cannot be reassigned, while the let variable 'x' can have different values within and outside the block.

User Ellabeauty
by
7.8k points