1

enter image description here

I expected same output from the two loops

var arr = [5,6,7,8]
// first loop 
for(var i=0;i<arr.length;i++) {
  setTimeout(()=>{console.log(i,arr[i])},500)
}
// second loop 
for(let i=0;i<arr.length;i++) {
  setTimeout(()=>{console.log(i,arr[i])},500)
}

does let and var can change the closure property of any function especially in this case?

Viraj Singh
  • 1,951
  • 1
  • 17
  • 27

1 Answers1

2

This is because of the lexical scope.

let will keep the variable value but var will update the value even before the first setTimeout callback will get executed.

Nikhil Goyal
  • 1,945
  • 1
  • 9
  • 17