FrontendDeveloper.in

JavaScript question detail

What is the purpose of the let keyword

The let keyword in JavaScript is used to declare a block-scoped local variable. This means that variables declared with let are only accessible within the block, statement, or expression where they are defined. This is a significant improvement over the older var keyword, which is function-scoped (or globally-scoped if declared outside a function), and does not respect block-level scoping.

Key Features of let:

  • Block Scope: The variable exists only within the nearest enclosing block (e.g., inside an {} pair).
  • No Hoisting Issues: While let declarations are hoisted, they are not initialized until the code defining them is executed. Accessing them before declaration results in a ReferenceError (temporal dead zone).
  • No Redeclaration: The same variable cannot be declared twice in the same scope with let.

Example:

let counter = 30;
if (counter === 30) {
let counter = 31;
console.log(counter); // Output: 31 (block-scoped variable inside if-block)
}
console.log(counter); // Output: 30 (outer variable, unaffected by inner block)

In this example, the counter inside the if block is a separate variable from the one outside. The let keyword ensures that both have their own distinct scope.

In summary, you need to use let when you want variables to be limited to the block in which they are defined, preventing accidental overwrites and bugs related to variable scope.

Back to all JavaScript questions
Get LinkedIn Premium at Rs 399