In ES6, let
and const
were introduced as new ways to declare variables. Here are the main differences between them:
Scope
Both let
and const
declare variables with block scope rather than function scope. This means that the variable is only available within the block { }
it is defined in:
{
let x = 1;
const y = 2;
}
console.log(x); // ReferenceError
console.log(y); // ReferenceError
Compare this to var
which has function scope:
{
var x = 1;
}
console.log(x); // 1
Reassignment
Variables declared with let
can be reassigned:
let x = 1;
x = 2; // Okay
While variables declared with const
cannot be reassigned:
const y = 1;
y = 2; // TypeError: invalid assignment to const `y`
Initialization
let
variables do not have to be initialized when declared:
let x;
x = 1;
While const
variables must be initialized when declared:
const y; // SyntaxError
Mutation
While const
variables cannot be reassigned, they can be mutated:
const array = [1, 2, 3];
array.push(4);
console.log(array); // [1, 2, 3, 4]
This is because const
only prevents reassigning the variable identifier to a completely new value - it does not make the value itself immutable.
Usage
In general, you should use:
let
when you know the variable will need to changeconst
by default, then only change tolet
if you find you do need to reassign the variable
Using const
by default makes your intent clearer - that the variable is meant to be constant. Only switching to let
if truly needed.
Hope this explanation helped! Let me know if you have any other questions.