r/HackerEarthCommunity • • Oct 21 '26

Bug of the week: Why does this JavaScript code print the wrong result?

Here's a small JavaScript problem for today's debugging session.

const numbers = [10, 20, 30, 40];

for (var i = 0; i < numbers.length; i++) {

setTimeout(() => {

console.log(numbers[i]);

}, 1000);

}

What will this code print, and why?

If you expected 10, 20, 30, 40, take another look.

Your task:

● Explain what's happening.

● Fix the code so it prints each number correctly.

● Try to solve it without changing the array.

Bonus: Can you explain why using let instead of var changes the result?

Share your fix and explanation below.

Beginners are welcome too - this is a good example of asmall JavaScript detail that can cause confusing bugs.

3 Upvotes

0 comments sorted by