JS Coding Questions Logo
JS Coding Questions
#18💼 Interview💻 Code

What is the purpose of the let keyword

Advertisement

728x90

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:

javascript
1let counter = 30;
2
3if (counter === 30) {
4
5let counter = 31;
6
7console.log(counter); // Output: 31 (block-scoped variable inside if-block)
8}
9
10console.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.

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 19

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
18of476