Show List
let and const
In ES6 (ECMAScript 2015), let
and const
are two new ways to declare variables, alongside the traditional var
. Here's a breakdown of each:
let
:- Variables declared with
let
have block scope, which means they are only accessible within the block they are declared in (a block is defined by curly braces{}
). - Variables declared with
let
can be reassigned. - Variables declared with
let
are not hoisted to the top of their scope.
- Variables declared with
Example:
// Using let to declare a variable
let x = 10;
if (true) {
let y = 20;
console.log(x); // Output: 10
console.log(y); // Output: 20
}
console.log(x); // Output: 10
console.log(y); // Error: y is not defined (y is not accessible outside the if block)
const
:- Variables declared with
const
also have block scope. - Variables declared with
const
cannot be reassigned. - However, for objects and arrays declared with
const
, their properties or elements can be modified.
- Variables declared with
Example:
// Using const to declare a constant
const PI = 3.14;
// PI = 3.1415; // Error: Assignment to constant variable.
const person = {
name: 'John',
age: 30
};
person.age = 31; // Valid: Modifying the properties of a constant object
console.log(person.age); // Output: 31
const numbers = [1, 2, 3];
numbers.push(4); // Valid: Modifying the elements of a constant array
console.log(numbers); // Output: [1, 2, 3, 4]
Using const
is encouraged when you want to declare variables that should not be reassigned, as it helps in writing more predictable and maintainable code. Use let
when you need to declare variables that may change their value.
Leave a Comment