What is let and const in JavaScript?

In JavaScript, let and const are two ways to declare variables. They were introduced in ES6 (ECMAScript 2015) to provide a better way to handle variable scopes compared to the traditional var keyword.

let

The let statement declares a block-scoped local variable, meaning the variable is only accessible within the block it is defined. This helps prevent variable hoisting issues and allows for cleaner code.

let x = 10; if (true) { let x = 20; // This x is different from the outer x console.log(x); // Output: 20 } console.log(x); // Output: 10

const

The const statement also declares a block-scoped local variable, but unlike let, the variable must be initialized at the time of declaration and cannot be reassigned later. However, if the variable holds an object, the properties of the object can still be modified.

const y = 30; // y = 40; // This will throw an error: Assignment to constant variable. const obj = { num: 50 }; obj.num = 60; // This is allowed console.log(obj.num); // Output: 60

let const JavaScript ES6 variable declaration block scope programming