Sometimes we write console.log() and the output surprises us.
This usually happens because of:
Scope issues
Closures
Asynchronous behavior
But letโs understand this in a very simple way.
๐น Simple Real-Life Example
Imagine you tell your friend:
โTell me the number after 2 seconds.โ
Now, before 2 seconds pass, you change the number.
When your friend finally speaks,
he tells the latest number, not the old one.
JavaScript works in a similar way.
Sometimes console.log() runs later,
and by that time the value has already changed.
๐น Simple Code Example
for (var i = 1; i <= 3; i++) {
setTimeout(() => {
console.log(i);
}, 1000);
}
You might expect:
1
2
3
But it prints:
3
3
3
Why?
Because:
var does not create block scope
The loop finishes first
i becomes 3
Then console.log() runs
So it prints the final value.
๐น The Real Reason (In Simple Words)
console.log() sometimes shows unexpected values because:
The variable changed before the log executed
JavaScript waited before running the code
Scope was not handled properly
One-line Summary
Most unexpected console.log() results happen because of scope or async timing.

Top comments (0)