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
.
Top comments (56)
Nonsense! github.com/getify/You-Dont-Know-JS...
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.
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.
Cancel VAR
The cancel culture is real. ;p
And yet I keep seeing it time and time again in tutorials. Sad.
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 ....
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.
6 years is nothing! I've seen PHP tutorials with methods 18 years past deprecation.
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.
I don't think I hardly ever would take advantage of variable hoisting in this way:
I agree that's problematic. But I don't want the language to complain at me, I want a configurable linter to complain at me. That's my objection to these errors. The language doesn't need to be my nanny. I am perfectly capable of choosing what rules I want enforced or not. And if it's a configurable and extensible tool, I can extend it to understand more nuances to when I want to allow disallow things. Once you bake an error enforcement into the language, you force that opinion on everyone, forever.
Moreover, there's many other ways that hoisting (and var) ARE helpful. For example:
Here, the
try..catch
construct is an "accidental" scope... IOW, I never intended it to be a scope. If I uselet
inside it, it becomes a scope when I don't want it to be. If I uselet
outside the block statement, I have to separate my declarations from my initial assignments, which I rarely like to do.Another example:
I generally prefer the loop to be treated like its own scope, but unfortunately, the
while
condition is not inside that scope, so I need thex
to be in an outer scope. But it doesn't make any sense semantically to declare it there, since it belongs to the loop.And also "function hoisting" is useful, for example in cases like this:
There are a variety of other edge cases and uses. But in summary: there are perfectly valid uses of
var
(or hoisting in general) that are not just stylistic preference or semantic in nature, but also functionally more desired.We should use
var
when it's helpful, uselet
when it's helpful, and (occasionally) useconst
if we really must.I teach
var
first because:let
andconst
and it's completely different to have a pure academic or a "theoretical" understanding of something and having real hands-on (for more than an hour or some tweet's worth of words) experience with something.let
andconst
to be used later in my curriculum where appropriate.I don't really know who this article is for, but sadly it seems to encourage ignorance in exchange for cool coins.
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...."
Var is actually used a lot in enterprise
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.
Here's the thing: you're entitled to your opinions on these things and I'm entitled to mine. I strongly disagree with every point you just made. But that doesn't really matter. Neither one of us is "right". So why should the language codify one set of opinions and make life harder for those who don't agree? Tools are where opinions belong, not languages.
lmaoo your explanation is more complete than the actual article
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.
disclaimer: let me start by saying that this is a very highly contested topic in JS.. with many different people throwing many different reasons for different using any one of these three over the others...
I would put myself quite firmly on the "
var
is dead! long livevar
!" bandwagon here... and not just because it leaks out of the current block scope. :phowever, to actually consider the full value of
var
, you need to keep in mind that it came about long before "block scoping". even just variable hoisting itself was not just one of those weird situations you needed to be aware of, it could be explicitly (ab)used to do some interesting things.. even if these were not considered "good practice", either way-back-when or in the current day.the most annoying part of many blog posts on this topic, has to be the nature of the coding examples given: where something will be shown leveraging the default behaviour of
let
(with it's block scoping restriction), then followed up with an overly verbose and borderline hacky implementation of the same final result usingvar
... and to top it off, this is all this before we even start on the accompanying changes introduced in ES6, since that is the real core of this eternalvar
vslet
/const
debate..--
topics like this feel akin to comparing a water bottle with a water tanker; they both hold liquid, they can both be opened and closed, they can both be moved, etc. etc., but they do so at different levels, in different ways, for different reasons.. so can we really compare them directly?
for variable assingment, we now have three different ways to assign something to a variable name. use the one that fits your needs, change it if you need to, and carry on with life. that's all there is to it.
at the end of the day, I would not recommend that anybody entirely abandons
var
, or even avoidslet
/const
... my suggestion is to work at understanding the quirks and gotchas of each, and to use whatever is most appropriate for your current requirements.@paritho I would suggest you amend your post a little, if for no other reason that to change the last sentence to read:
this did make me chuckle, quite loudly if I'm being honest:
Same here. But I teach beginners and coding style is the least of their worries and they need to be prepared to slot into the team they're hired onto.
This is an interesting observation that I've seen as well. IME, they just write sloppy or confusing code in general. It's always possible to write code that avoids the pitfalls of
var
entirely as long as the style is reasonable. What's weird is that the style of my reference solutions function identically when you refactor them to the "right" way and useconst
/let
. This is probably why it's so rare for my students get "tripped up" by the pitfalls ofvar
. When they do, the code they're writing makes no sense anyway, which is expected of beginners.Yes, you are absolutely right, which is why they're also equipped for that. The motivation behind my comments also boils down to your point. There are social pressures and media being produced that discourage thinking critically about how things work, and when they're appropriate. Often things get reduced to memes and jokes and if I "warn" them about anything, it's that they're going to encounter people, videos, and writings that are reductive and unproductive. They need to be careful not to trick themselves into thinking they're any better at building useful software by "agreeing" with anybody's lopsided opinions.
Some comments may only be visible to logged-in visitors. Sign in to view all comments.