DEV Community

Rahul Chaudhary
Rahul Chaudhary

Posted on

2

Guess the output

var a = 2;
if (true) {
var a = 5;
console.log(a) // 5
}
console.log(a) // 5

I'm new to Javascript, can anyone tell why it printed 5 in below console statement

Top comments (2)

Collapse
 
siddharthshyniben profile image
Siddharth

TL;DR If you use var this will happen, try using let


var is not block scoped, this is a limitation from the days of old JavaScript. Nowadays you should use the modern let or const.

Some resources:

Collapse
 
zippcodder profile image
Deon Rich

You overwrote the variable in the if statement.

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay