let and const in JavaScript (ES6)
JavaScript ES6 (ECMAScript 2015) introduced two new keywords for declaring variables: let and const. These keywords provide better variable scoping and immutability, respectively, compared to the older var keyword. Understanding when and how to use let and const is crucial for writing modern and efficient JavaScript code.
Using let for Block-Scoped Variables
The let keyword allows you to declare block-scoped variables, meaning they are limited to the block ({}) in which they are defined. This is different from var, which has function scope or global scope, depending on where it's declared.
let x = 10; // x is block-scoped to this block
console.log(x); // Output: 10
}
console.log(x); // Throws ReferenceError: x is not defined
Using let for Loop Variables
One common use case of let is in loops, where each iteration should have its own separate variable. Using var in loops can lead to unexpected behavior due to variable hoisting.
for (let i = 0; i < 5; i++) {
setTimeout(function() {
console.log(i); // Outputs 0, 1, 2, 3, 4 (each value after 1 second)
}, 1000 * i);
}
In this loop, each iteration creates a new block-scoped i variable, ensuring that the correct value of i is logged after each timeout.
Using const for Constants
The const keyword is used to declare constants, which are variables whose values cannot be reassigned after initialization. This ensures immutability and prevents accidental changes to critical values.
PI = 3.14159; // Throws TypeError: Assignment to constant variable.
Attempting to reassign a value to a constant variable results in a TypeError. Constants are typically used for values that should remain unchanged throughout the program.
Using const with Objects and Arrays
While const prevents reassignment of the variable itself, it does not make objects or arrays immutable. You can still modify the properties of an object or the elements of an array declared with const.
const person = { name: 'John', age: 30 };
person.age = 40; // Valid, modifies the age property
person.address = '123 Main St'; // Valid, adds a new property
Similarly, with arrays:
numbers.push(4); // Valid, adds an element to the array
numbers[0] = 0; // Valid, modifies the first element
Differences between let and const
- Reassignment: Variables declared with let can be reassigned new values, while variables declared with const cannot be reassigned after initialization.
- Block Scope: Both let and const have block scope, but const adds immutability within that scope.
- Hoisting: Variables declared with let and const are not hoisted to the top of their block, unlike var.
When to Use let vs const
Use let for variables that will be reassigned or have limited scope within a block.
Use const for constants and variables that should not be reassigned after initialization.
const MAX_VALUE = 100; // Use const for constants
Common Mistakes with let and const
- Not Initializing const: Constants declared with const must be initialized with a value; otherwise, it will result in an error.
- Mutating Constants: While you can modify properties of objects and elements of arrays declared with const, you cannot reassign them entirely.
const greeting; // Error: Missing initializer in const declaration
const person = { name: 'John' };
person = { name: 'Jane' }; // Error: Assignment to constant variable
Practice Excercise Practice now