4

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;
})()
Spawni
  • 83
  • 4

2 Answers2

7

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.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205
3

Where you can only use var variables but you want to ensure that a variable declaration is not going to overwrite another pre-existing variable of the same name, you can use an IIFE to scope that variable to the function. This in effect creates a "block", similar to the second example below.

var variables are scoped to functions:

var a = 1;
let b = 1;

(function() {
  var a = 2;
  let b = 1;
})();

console.log(a); //=> 1 (a is not overwritten because the second `var a` is function-scoped)
console.log(b); //=> 1

let variables are scoped to blocks:

let a = 1;
var b = 1;

{
  let a = 2;
  var b = 2;
}

console.log(a); //=> 1 (a is not overwritten as let is block-scoped)
console.log(b); //=> 2 (b is overwritten as var is not block-scoped)

It's worth mentioning that you can redeclare a var variable, hence why it would be possible to overwrite an existing var variable of the same name. However, you cannot redeclare a let variable:

var a = 1

// will not error as `var` does not prevent redeclaration
var a = 2

let b = 1

{
  // will not error as `b` is not declared in this block
  let b = 2
}

// will error as `b` is already declared in this scope
let b = 3

You can read more about let and var in this question and its answers.

sdgluck
  • 18,456
  • 4
  • 56
  • 83