DEV Community

loading...

Why let was introduced in Javascript

Akshat Sharma
Passionate about Engineering & Promoting Engineers
・1 min read

See this code

use strict
function f() {
  if (true) {
    var x = 1
  }
  return x
}

Try to run this function, and it will return '1'

Now see this

use strict
function f() {
  if (true) {
    let x = 1
  }
  return x
}

Try to run this function, and it will throw error.

Why?

Logically anything scoped inside if shouldn't be accessible outside, but 'var' was accessible outside, thats why in ECMA2015 JS introduced 'let' to achieve this.

Discussion (1)

Collapse
andrewrothman profile image
Andrew Rothman

In case anyone is interested, I think this behavior is called "hoisting". Is that right?