JavaScript `let` and `const`
1. Introduction
In JavaScript, let and const are used for declaring variables. They provide block-scoped variables, which can make your code easier to understand and less error-prone compared to the traditional var keyword.
2. `let`
The let keyword is used to declare a block-scoped variable. It allows the variable to be reassigned. Unlike var, let is not function-scoped but block-scoped.
Example:
function exampleLet() {
if (true) {
let x = 10;
console.log(x); // 10
}
console.log(x); // ReferenceError: x is not defined
}
exampleLet();
In this example, x is accessible only within the if block. Attempting to access x outside the block results in a ReferenceError.
3. `const`
The const keyword is used to declare a block-scoped variable that cannot be reassigned after its initial assignment. However, if the variable holds an object or array, its properties or elements can still be modified.
Example:
function exampleConst() {
if (true) {
const y = 20;
console.log(y); // 20
// y = 30; // TypeError: Assignment to constant variable
}
console.log(y); // ReferenceError: y is not defined
}
exampleConst();
In this example, y is block-scoped and cannot be reassigned. Attempting to reassign y results in a TypeError.
4. Key Differences
- Scope: Both
letandconstare block-scoped, whilevaris function-scoped or globally scoped. - Reassignment:
letallows reassignment, whileconstdoes not. However, objects or arrays declared withconstcan still be modified. - Hoisting: Both
letandconstare hoisted but are not initialized. They are in a "temporal dead zone" from the start of the block until the declaration is encountered. - Usage: Use
letwhen you need a variable that will change value. Useconstfor variables that should not be reassigned after their initial assignment.
5. Example with Both `let` and `const`
function example() {
if (true) {
let a = 1;
const b = 2;
a = 3; // Allowed
// b = 4; // Error: Assignment to constant variable
console.log(a); // 3
console.log(b); // 2
}
// console.log(a); // Error: a is not defined
// console.log(b); // Error: b is not defined
}
example();
This example demonstrates the usage of both let and const. a can be reassigned, while b cannot. Both variables are only accessible within the block.