DEV Community

Shashi Bhushan Kumar
Shashi Bhushan Kumar

Posted on

Why Does console.log() Sometimes Show Unexpected Values in JavaScript?

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);
}

Enter fullscreen mode Exit fullscreen mode

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)