Stop being the product.
Become the owner.
or
sign uplog in

Why does this JavaScript code print an unexpected result…

Why does this JavaScript code print an unexpected result?

I came across this small JavaScript example and the output surprised me.
for (var i = 0; i < 3; i++) {

setTimeout(function () {

console.log(i);

}, 1000);

}

When this runs, the output is:
3
3
3

But I expected it to print:
0

1

2
Why does this happen in JavaScript?
What would be the correct way to fix this behavior?
#dev #programming #js #technology
loved
1
laughed
1
earnings
9,000 mlx total
$0  total
engagement
5 views
2 reactions

1 comments

badge
$0 earned7mo ago
everything behave well at night in bed 😂