let and const Explained
Key Concepts
- let
- const
- Block Scope
- Temporal Dead Zone
- Reassignment
- Mutability
let
let is a keyword used to declare variables that are block-scoped. This means that the variable is only accessible within the block in which it is defined.
Example:
if (true) {
let x = 10;
console.log(x); // Outputs: 10
}
console.log(x); // ReferenceError: x is not defined
const
const is used to declare variables that are block-scoped and cannot be reassigned after their initial value is set. However, the contents of the variable can still be mutable if it is an object or array.
Example:
const y = 20;
y = 30; // TypeError: Assignment to constant variable.
const obj = { key: "value" };
obj.key = "new value"; // This is allowed
Block Scope
Block scope refers to the visibility of variables within a block of code, defined by curly braces {}. Variables declared with let and const are block-scoped, meaning they are only accessible within the block they are defined.
Example:
{
let z = 30;
const w = 40;
console.log(z); // Outputs: 30
console.log(w); // Outputs: 40
}
console.log(z); // ReferenceError: z is not defined
console.log(w); // ReferenceError: w is not defined
Temporal Dead Zone
The Temporal Dead Zone (TDZ) is the period between entering a scope and the actual declaration of a variable. During this period, the variable is in a "dead zone" and accessing it will result in a ReferenceError.
Example:
console.log(a); // ReferenceError: Cannot access 'a' before initialization
let a = 5;
Reassignment
Variables declared with let can be reassigned to a new value, whereas variables declared with const cannot be reassigned.
Example:
let b = 10;
b = 20; // This is allowed
const c = 30;
c = 40; // TypeError: Assignment to constant variable.
Mutability
While const variables cannot be reassigned, their contents can still be mutable if they are objects or arrays. This means you can change the properties of an object or the elements of an array declared with const.
Example:
const arr = [1, 2, 3];
arr.push(4); // This is allowed
console.log(arr); // Outputs: [1, 2, 3, 4]
const obj = { key: "value" };
obj.key = "new value"; // This is allowed
console.log(obj); // Outputs: { key: "new value" }