-1

Can someone explain to me why the code does not act as expected?

WHy would this happen? I know it is due to "scoping", but I don't know the exact mechanism.

"Considering the above code, the console will display four identical messages "The value undefined is at index: 4". "

const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
      setTimeout(function() {
           console.log(`The value ${arr[i]} is at index: ${i}`);
      }, (i+1) * 1000);
}

declare i using 'let' solves the problem;

putting setTimeOut() into IIFE also solves the problem, but I could not understand why.

Jianyuan Chen
  • 53
  • 2
  • 9
  • Similar question [here](https://stackoverflow.com/questions/11200279/return-a-function-from-the-anonymous-wrapper) – sabithpocker Dec 09 '17 at 09:24
  • If you know, it is because of 'scoping', why not read up on it? There are plenty of resources on the web and StackOverflow is not really ment for teaching. – Syntac Dec 09 '17 at 09:24
  • It is a common gotcha that functions defined in for loops don't work as you may expect – Patrick Hund Dec 09 '17 at 09:25

1 Answers1

0

let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.