DEV Community

Piotr Wilk
Piotr Wilk

Posted on

Is it the end of var? Here’s a better solution known for years.

Var is a great thing. It served people well all across the world for years. But its time has passed. No one likes it anymore and now we all know it can even cause serious problems. Luckily there’s a better solution and it’s been a while since it was released (June 2015!). Why then do people still use var?

Ok, this is not about football, as some of you probably may think. Of course it’s about JavaScript. I’m a React Native developer, right? It has to be about JS.

Let me take you to the point.

Yep, a replacement for var is obviously let and const. How is it different from this var everyone hates now?

The scope

Scope of var is the whole body of the function it’s declared in. Not a tragedy. But when it’s declared outside of a function, the scope is global. Now this is bad news. It can lead you to some unexpected or even unpredictable stuff in your code.

Scope of let and const on the other hand is only a block. A block, means i.e. a function, but also if/else statement, for/while loops, switch/case statements and whatnot. Basically, it’s between the brackets {}. So this is much more reliable and much safer to use because it stays exactly where you declared it. It won’t go outside.

What’s more, const will make you sure the value of what you declared will not be changed in the future. How great is that?

The end of var?

To be honest, I don’t even remember the last time I have used var instead of let or const. I’m not sure of statistics, but it’s also less and less seen in existing legacy projects I work on. Of course var has its use cases, but there aren’t many of them and still, we can do better than that.

Joke’s over

Ok, I won’t say more here. There have been a ton of blog posts written since let and const were first introduced, this one is more like a social experiment. I hope you already forgave me the clickbaitish title!

Top comments (0)