1Explanation From Medium:
2
3//https://medium.com/brandsoft/variable-scope-and-iifes-in-javascript-3cf85f79597e#:~:text=By%20using%20an%20IIFE%2C%20we,when%20the%20IIFE%20is%20executed.
4
5Code:
6
7// for (var i = 0; i<=5; i++){ // this type of problem created
8// setTimeout(function (){
9// console.log('Current Value is ' + i);
10// }, 1000 * i)
11// }
12
13// for (var i = 0; i <= 5; i++) {
14// (function (n) { // to avoid previous example's fault
15// setTimeout(function () {
16// console.log('Current Value is ' + n);
17// }, 1000 * n)
18// })(i);
19// }
20
21// for (let i = 0; i<=5; i++){ // in this case (let) behaves different from var
22// setTimeout(function (){
23// console.log(i);
24// }, 1000 * i)
25// }
26