DEV Community

Paul Thompson
Paul Thompson

Posted on • Updated on

3 reasons to use 'var' in JavaScript

The var keyword was JavaScript's first way to declare a variable. It fits, right? Var, variable, it's in the name. But like the Joker, var is more than pretty face -- it has some baggage. As a beginning programmer, or a seasoned one dipping your toe into the seedy underbelly of JavaScript development, you maybe be wondering when you should use var to declare your JavaScript objects and functions.

Never fear. I have 3 reasons for you to use var in your next JavaScript project.

You love tradition and spurn anything new

Var may be the oldest keyword to declare a variable, but it is by far the only one. It's younger cousins, let and const exploded onto the scene with ES6 (over 6 years ago as of this writing!). But if sticking to old norms fraught with perils is your thing, keep using var and leave these upstart keywords to listen to their terrible pop music and complain about their parents.

You prefer mutability, even when you don't

Var has the troubling distinction of creating a variable of any type, which can then be changed to a variable of any type later. That's right, the number you declared on line 4 just became a string on line 17 and a boolean on line 109. This type flexibility is a key feature of JavaScript, but it can be avoided. But if you too like to live dangerously, keep using var.

You like leaky scopes

Prior to ES6, JavaScript variables were always defined at the function scope. In a lot of cases, this meant variables were global. JavaScript didn't enforce block-level scopes such as inside a for loop or if block. So a variable declared with var would be hoisted to the top of its function scope. In other words, the variable declaration moved to the top of the current lexical environment with a value of undefined. A common issue arising from hoisting is that such variables are accessible outside the block scope, where the developer may not expect them to be.

A subtler and more difficult to detect bug can happen here as well, variable shadowing. Rarely this may be desired. If that is you, var is your hero.

There must be a better way

If you made it this far, you're probably seconds away from pounding out a fierce comment about how I'm wrong about var. The truth is, no one should be using var in any JavaScript code except for a history lesson. Even then, it should come with a footnote that says something like, "please don't ever do this."

Let and const have been available in every major browser for the last 6 years. This is really, really ancient in frontend years. var isn't just the parent misunderstanding their teen, it's the great grandparent everyone loves but no one invites to the fun parties.

Let retains JavaScript's flexible type system while enabling block-scoping. Const creates a -- you guessed it -- constant variable in block-scope. Const creates a variable that cannot be reassigned, but similar to most other languages, const objects can have their properties mutated. These two alternatives to var should cover every use case you have. Even if you are in the tough spot of needing to support truly archaic browsers, don't use var. Use a tool such as Babel.

So please, please, do not use var.

Oldest comments (56)

Collapse
 
paritho profile image
Paul Thompson

And yet I keep seeing it time and time again in tutorials. Sad.

Collapse
 
baenencalin profile image
Calin Baenen

My school uses Code HS with this dog named Karel, and a pet peeve of mine is that they use var.
The teacher doesn't even address them, as they basically have no education on the language itself (they're just permitted and appointed to teach it).

Even as someone who barely uses JS, this annoys the fuck out of me.

Collapse
 
thumbone profile image
Bernd Wechner • Edited

All language updates take time to trickle through. It is the way of the internet. I mean search the web with any technical question and rail, as most of us do, at any articles that are not presenting their publication date clearly, as stuff simply gets dated but still always found. I think we'll be reading Python 2 solutions to problems on web search results for years to come yet for example ....

Thread Thread
 
digitaldevourer profile image
DigitalDevourer

Hate when that happens.
You're ½ way through when things start to feel off, and now it's become a hunt for the date.
Worst of all are the "SEO-based" articles that update their titles or keywords to match popular searches, despite having almost no related content or are years too late.

Collapse
 
emptyother profile image
emptyother

6 years is nothing! I've seen PHP tutorials with methods 18 years past deprecation.

Collapse
 
thumbone profile image
Bernd Wechner

Love the faux title ... ;-)

Collapse
 
raibtoffoletto profile image
Raí B. Toffoletto

Ufff.... I came here hoping that the title was sarcastic, but for a moment in the first paragraph I worried that you were REALLY to defend VAR.... 🤣. Nice writing 👍 and let's all chant "die VAR, die...."

Collapse
 
koire profile image
Koire

Var is actually used a lot in enterprise

Collapse
 
raibtoffoletto profile image
Raí B. Toffoletto

I'm not saying to go back and alter legacy code, but in 2021 you should not be writing JS with var... enterprise is a ship difficult to steer, but you can do it slowly. I don't shame on my colleagues still using jQuery to build stuff, but you can use const and let with jQuery.

Collapse
 
abhishekraj272 profile image
Abhishek Raj

What do you think babel does to your let and const 🙃

Collapse
 
koire profile image
Koire

Don't forget code golf!
Let's scope is more constrained than var, so you (maybe) can't do as many tricks with let as var.
And const is 2 more characters! That's unforgivable

Collapse
 
paritho profile image
Paul Thompson

There are actually a lot of really cool exploits you can do in JS because of it. Golf coding is amazing!

Collapse
 
fyodorio profile image
Fyodor

Anything can be a weapon in hands of a mighty ninja...

Collapse
 
emptyother profile image
emptyother

Two "good" reasons I still use var:

  • ~Old projects that need to support IE11 and isnt transpiled.~ Oh, right, even IE11 supports let and const. Well almost, it still have a few gotchas that will never be fixed.
  • I'm also writing C# and var is stuck in my fingers. Sometimes I even miss the eslint warnings about it. Darn muscle memory.
Collapse
 
aequinn profile image
Anthony Quinn

Number 3: kind of like old projects, you are doing any JavaScript variables in Google Tag manager, they still force you to use var, I develop the scripts with the new and am forced to roll it back to the old when try to save.

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

Same here, I also came here looking for outrage but then read the headings :D

Top tier clickbait

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

A friend was learning JS at school until not long ago, and they were still learning var, HXR and function (as in, unscoped function declarations that end up in window by default).

Collapse
 
morewry profile image
Rhy Moore

What about hoisting?

Collapse
 
getify profile image
Kyle Simpson
Collapse
 
dagr8 profile image
DAGr8

Cancel VAR
The cancel culture is real. ;p

Collapse
 
sabbakilam profile image
SabbaKilam

Thanks for the rational clarification. Nuanced treatment of this topic is rare.
I've never liked const. I'll start using var again for function scoping.

Collapse
 
sabbakilam profile image
SabbaKilam

Thanks for the rational clarification. Nuanced treatment of this topic is rare.
I've never liked const. I'll start using var again for function scoping.

Collapse
 
mtrantalainen profile image
Mikko Rantalainen • Edited

The only reason to use 'var' is to be compatible with some old info tv systems which have some weird more or less broken HTML renderers. There you cannot use any automated tools either because nobody really wants to support those things so you have to write fully custom implementations. If you don't need to support such things you shouldn't use 'var' anymore.

Collapse
 
synrec profile image
Synrec

Unfortunately the engine I use for my project means I have to use var.

Have gotten rather creative in avoiding overlaps in var names tho.

Collapse
 
lonyyy profile image
lonyyy

lmaoo your explanation is more complete than the actual article

Collapse
 
meliodas profile image
Henry Onyango

There are reasons to still use var. There's nothing with var. It's not broken. It's important you understand how it works and when is most appropriate to use it.

Collapse
 
paritho profile image
Paul Thompson

I'd be interested in hearing when it is appropriate to use it

Collapse
 
meliodas profile image
Henry Onyango

Look at the section "making the case for var"
github.com/getify/You-Dont-Know-JS...

Some comments may only be visible to logged-in visitors. Sign in to view all comments.