Trusted answers to developer questions

What is the let keyword in JavaScript?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

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:

function func() {
// x is known here but not defined.
console.log('value of x here: ', x)
{
var x = 10;
x = x + 5;
}
// x is still known here and has a value.
console.log('value of x after for block: ', x)
}
// x is NOT known here.
func()

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:

let mango = "yellow"
if (mango === "yellow"){
let mango = "blue"
console.log(mango)
}
console.log(mango)

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.

RELATED TAGS

let
javascript
js
variable
Copyright ©2024 Educative, Inc. All rights reserved
Did you find this helpful?