Javascript Questions
- What will the following code output?
This question deals with the topics: closures, setTimeout, and scoping. The correct answer to this is question is:const arr = [10, 12, 15, 21];
for (var i = 0; i < arr.length; i++) {
setTimeout(function() {
console.log('Index: ' + i + ', element: ' + arr[i]);
}, 3000);
}
Index: 4, element: undefined(printed 4 times).
The reason for this is because the setTimeout function creates a function (the closure) that has access to its outer scope, which is the loop that contains the index i. After 3 seconds go by, the function is executed and it prints out the value of i, which at the end of the loop is at 4 because it cycles through 0, 1, 2, 3, 4 and the loop finally stops at 4.arr[4] does not exist, which is why you get undefined.
Excellent and useful blog, thanks for taking time to share this code admin.
ReplyDeleteSpring Training in Chennai | Spring Hibernate Training in Chennai | Struts Training center in Chennai