singularity

Closures

What is a closure?

How do closures work?

How are different scopes linked?

What causes this problem?


for (var i = 1; i <= 3; i++) {
  setTimeout(() => {
    console.log(i);
  }, 1000);
}

// 4 4 4

How to resolve this problem?


for (let i = 1; i <= 3; i++) {
  setTimeout(() => {
    console.log(i);
  }, 1000);
}

// 1 2 3

for (var i = 1; i <= 3; i++) {
  ((counter)=>{
    setTimeout(() => {
      console.log(i);
    }, 1000);
  })(i)
}

// 1 2 3 

emulating private methods with closures