0

I came accross following question and I simply cannot understand it, how it got the output. Can someone explain?

<html>
<head></head>
<body>

<script>
const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
  setTimeout(function() {
console.log('Index: ' + i + ', element: ' + arr[i]);
  }, 3000);
}
</script>

</body>
</html>

Expected:

Index: 0, element: 10
Index: 1, element: 12
Index: 2, element: 15
Index: 3, element: 21

Output:

Index: 4, element: undefined (4 times)

It doesn't make any sense, how this is the output.

Deadpool
  • 7,811
  • 9
  • 44
  • 88
  • You can refer to the following link for more details. https://medium.com/coderbyte/a-tricky-javascript-interview-question-asked-by-google-and-amazon-48d212890703 – Aalind Sharma Apr 02 '18 at 09:34
  • It cannot be explained. Not the output you get. However, if the output is four lines of `Index: 4, element: undefined` then it makes perfect sense. The `console.log()` is executed long after the for loop has ended. At that stage the value of `i` is 4 and `arr[4]` is undefined. – KIKO Software Apr 02 '18 at 09:35
  • const arr = [10, 12, 15, 21]; for (var i = 0; i < arr.length; i++) { setTimeout(function(i) { console.log('Index: ' + i + ', element: ' + arr[i]); }(i), 3000); } use this – Pankaj Bisht Apr 02 '18 at 09:36

0 Answers0