As per my understanding, the below function should print 5 five times because of hoisting . But instead, it prints 6 five times .
Question is, how come it prints 6 when the loop's limit is <=5
?
function () {
for ( var i = 1; i <= 5; i++) {
setTimeout( function() {
console.log(i); // 👈 this should print '5' five times
}, i * 1000)
}
}
It prints 6 because that's the value of i
when the loop exits.
Consider the flow at the end of the loop's run, when i
is 4:
The for loop stops after the i++
occurs which meets the condition for exiting (ie 6 > 5
) - at that point, the value of i
has incremented to 6
already and about a second later the value of i
is printed
It is because of the increment you apply sol =>
function num() {
for ( var i = 1; i <= 4; i++) {
setTimeout( function() {
console.log(i); // 👈 this should print '5' five times
}, i * 1000)
}
}
num()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.