Junior
What is the difference between let and const?
sobes.tech AI
Answer from AI
let:
- Declares a variable with block scope.
- The variable can be reassigned.
- Cannot be redeclared in the same scope.
const:
- Declares a constant with block scope.
- The value cannot be reassigned (for primitives). For objects and arrays, their contents can be modified, but not the reference itself.
- Must be initialized at the time of declaration.
- Cannot be redeclared in the same scope.
// let
let count = 0;
count = 1; // Allowed
// let count = 2; // Error: Cannot redeclare block-scoped variable 'count'.
// const
const maxItems = 10;
// maxItems = 11; // Error: Assignment to constant variable.
const user = { name: 'Alice' };
user.name = 'Bob'; // Allowed, object content can be changed
// const PI; // Error: Missing initializer in const declaration
Using const is preferable if the variable's value is not intended to change, as it improves code readability and prevents accidental reassignment. let is used when the variable's value will change.