What is the let keyword in JavaScript?

The let keyword is used to declare variables in JavaScript. The var keyword can also be used to declare variables, but the key difference between them lies in their scopes. var is function scoped while let is block scoped - we will discuss this in more detail later.

To understand the let keyword, it is important to understand how it differs from var

svg viewer

Function Scope

Consider the example below:

In the code snippet above, the first tab uses var, note how var is declared in line 5, inside a block. This variable is known (but undefined) above the block. However, it is known and defined after the block.

The highlighted lines represent the areas where x has a scope. Since it is the entire function itself, var is said to have function scope.

In the second code tab that declares x using let in line 5, note that it is only known and defined within the block it is declared in - the highlighted lines. It is out of scope everywhere outside its block.

Try uncommenting all the console.log(x) statements in the code that uses let and note how JavaScript throws an error.


Block scope

Consider the example below which will highlight the block scope for let more clearly:

Using let

mango is declared as "yellow" in line 1, and redeclared as "blue" in line 4 - inside the if block. However, as the output shows, the mango declared inside the if block has scope within that block only. Outside this block, the original mango variable set to "yellow" is available.

Using var

Conversely, in the code that uses var, redeclaration of mango to "blue" inside the if block, also changes the mango declared in line 1 to "blue". This is because variables declared with var are defined globally, regardless of block scope.

Copyright ©2024 Educative, Inc. All rights reserved