DEV Community

Akshat Sharma
Akshat Sharma

Posted on

Why let was introduced in Javascript

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.

Top comments (1)

Collapse
 
andrewrothman profile image
Andrew Rothman

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