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.