DEV Community

Anil Kumar Khandei
Anil Kumar Khandei

Posted on

4 1

JS Var vs Let difference

The difference between var and let in JavaScript is block scope.

var

When a var is declared outside a block scope, and then re declared inside a block after the first declaration. The value of the var gets changed after the block scope is over.

//first declaration of var x
 var x=10;
 {
     //second declaration of var x
     var x=5;
     alert(x); //prints 5
 }
 alert(x); //prints 5
Enter fullscreen mode Exit fullscreen mode

let

However by using let keyword to declare a variable. the value of the variable doesn't get changed by the subsequent re declaration inside the block.

//first declaration of let var y
 let y=15;
 {
     //second declaration of let var y
     let y=90;
     alert(y); //prints 90
 }
 alert(y); //prints 15
Enter fullscreen mode Exit fullscreen mode

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

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

Okay