Search code examples
javascriptvarlet

JavaScript: implement let-working with var


So I have a code that clone let-behavior. But I don't undestand how and why it is working. Can someone explain it?

(function() {
  var a = 2;
})()

Solution

  • let is scoped to the block it appears in.

    var is scoped to the function it appears in.

    By replacing a block with a function (which is immediately invoked) var is scoped to the same lines of code as let would be.