Let vs Var in JavaScript

What’s the difference between the let keyword and the var keyword in JavaScript? It looks like they both do the same thing.

let and var behave similarly to one another. The main difference is let has slightly different, more restrictive scoping rules to var.

Before let was introduced, Javascript had two types of scoping - global scope and function scope. Unlike most other languages which use blocks to denote variable scoping. This was a major source of bugs in Javascript.

When var is used within a function, the resulting variable’s scope is accessible by the entire function, let on the other hand declares variables with block-level scope, ensuring variables are only accessible in the block they’re declared in.

Here’s an example using var.

for (var i = 0; i < 5; i++) {
    console.log("Inside: " + i)
}
console.log("Outside: " + i)

Notice how after the for loop has completed, the i variable is still accessible.

for (let i = 0; i < 5; i++) {
    console.log("Inside: " + i)
}
console.log("Outside: " + i)

When using let this code will fail because the i variable has only block level scope - it’s not accessible outside of the block it was declared in, as is the case in most other programming languages.

There’s actually a video on this too:

2 Likes