DEV Community

3 reasons to use 'var' in JavaScript

Paul Thompson on November 08, 2021

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 ...
Collapse
 
getify profile image
Kyle Simpson
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
 
dagr8 profile image
DAGr8

Cancel VAR
The cancel culture is real. ;p

Collapse
 
paritho profile image
Paul Thompson

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

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
 
calinzbaenen 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
 
getify profile image
Kyle Simpson

I don't think I hardly ever would take advantage of variable hoisting in this way:

x = 2;

// later:
var x;
Enter fullscreen mode Exit fullscreen mode

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:

try {
   var x = whatever(42);
}
catch (err) {
   var x = "oops";
}

console.log(x);
Enter fullscreen mode Exit fullscreen mode

Here, the try..catch construct is an "accidental" scope... IOW, I never intended it to be a scope. If I use let inside it, it becomes a scope when I don't want it to be. If I use let outside the block statement, I have to separate my declarations from my initial assignments, which I rarely like to do.

Another example:

do {
   var x = whatever(42);
}
while (x < 100);
Enter fullscreen mode Exit fullscreen mode

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 the x 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:

fn = wrapWithSomeBehavior(fn);

// later:
function fn(whatever) {
  // ..
}
Enter fullscreen mode Exit fullscreen mode

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, use let when it's helpful, and (occasionally) use const if we really must.

Collapse
 
thebearingedge profile image
Tim Davis

I teach var first because:

  1. It's still out there and I don't want my students seeing it at work and thinking "why didn't my teacher tell me about something so basic?"
  2. It behaves differently from let and const 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.
  3. Knowing about and being competent when dealing with all three is better than knowing about and being competent when dealing with only two of the three (66% is a D, great job).
  4. Block scoping is a good transform output to demonstrate when teaching Babel.
  5. I ask for let and const 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.

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.

 
getify profile image
Kyle Simpson

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.

Collapse
 
lonyyy profile image
lonyyy

lmaoo your explanation is more complete than the actual article

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
 
zalithka profile image
Andre Greeff

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 live var!" bandwagon here... and not just because it leaks out of the current block scope. :p

however, 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 using var... 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 eternal var vs let/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 avoids let/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:

So please, please, do not use var without carefully considering your current unique use case.


this did make me chuckle, quite loudly if I'm being honest:

var isn't just the parent misunderstanding their teen, it's the great grandparent everyone loves but no one invites to the fun parties.

 
thebearingedge profile image
Tim Davis • Edited

For mine, let and const are way more useful than var, so I avoid var and in my personal projects I have linting rules against it.

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.

There are folks with other coding styles that rely on hoisting, redeclaration and leaky block scopes that benefit from var, so for them it makes sense to do the opposite and stick to var and maybe even ban let or const in their linting rules.

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 use const / let. This is probably why it's so rare for my students get "tripped up" by the pitfalls of var. When they do, the code they're writing makes no sense anyway, which is expected of beginners.

One thing is clear, and is that is way more popular to prefer let/const.

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.

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 🏳️‍⚧️

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
 
sabbakilam profile image
SabbaKilam

I always use var at the browser's console so that I can re-declare and re-assign variables at will, hassle-free, while playing around and testing concepts. Otherwise, I get clobbered with error messages and restrictions.

Collapse
 
andyhilton profile image
Andy Hilton

Why didn't let just replace var? If the whole world is against it why does it still exist?

Collapse
 
paritho profile image
Paul Thompson

The EcmaScript committee has strict guidelines to 'not break the web'. Meaning, old JS code must always work.

Collapse
 
koire profile image
Koire

Also let is scoped

Collapse
 
emptyother profile image
emptyother

Nobody want to dig up and rewrite their 10 year old production code. But eventually it too will go the way of elem.attachEvent() and the <blink> tag.

 
koire profile image
Koire • Edited

We don't always write var but for IE but we definitely transpile it
I still have projects that warn you you need IE 5 or later for it to work correctly.

Edit
There is the case where someone might come in and say "var bad" and use replace to turn them all to let or const and break everything in a legacy system because it was being funky

Collapse
 
thebearingedge profile image
Tim Davis • Edited

Did you teach them about eval, with and other old stuff as well?

that's not really what this is about.

I mean I get that you want to teach old stuff for context, but you should be very clear about avoiding var.

I've yet to hear any real argument for this.

Babel no longer does those transformation from let and const to var unless you explicitly configure it to do so. Go and check the Babel REPL.

I addressed this already.

I agree we should know about var, but one thing is knowing about it and other is actually using it.

My point is that you don't know something unless you have used it.

Collapse
 
matttepp profile image
Matyáš Teplý

They had us in the first half, not gonna lie.

Collapse
 
andrebradshaw profile image
Andre Bradshaw

Let and const are useful, but when people say var should never be used, I immediately start to question if they have done any interesting development in JS.

Additionally, for beginners, I would argue that using var forces people to deal with unexpected behaviors which is a useful method for actually learning how JS works.

Collapse
 
darkwiiplayer profile image
𒎏Wii 🏳️‍⚧️

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

Top tier clickbait

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...

Collapse
 
abhishekraj272 profile image
Abhishek Raj

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

Collapse
 
getify profile image
Kyle Simpson

I taught eval and with for years, specifically so people understood why they shouldn't be used.

 
andersoncdz profile image
anderson • Edited

Kids learn javascript and think they know something. What do you know about php, especially from version 8.x?
Today in the market anyone who takes a python or Nodejs course thinks they know something.
It will work with C#, C++ or even C. I've already come across a heap of garbage written in NodeJs.
These kids programmers get into projects, which when they start to grow they become a bunch of junk.
I've been programming in javascript for 15 years, before that I had to learn patterns and other ways to work around certain problems. The problem is not language but who uses it, in these 15 years I have come across bad codes, but I have also come across excellent codes, of course using Var, but who knew what they were doing.
I believe the introduction of let was more to prevent novice programmers from screwing up, as well as the syntatic sugar Class, which actually uses prototype behind the scenes.
You happen to already have the source code of VueJs for example, many people who are annoying people who use VAR, if you open the source code the vue as I said you will find var inside, the difference is that it was used in a prudent way something that only seniors will know, and not kids from 20-hour courses.

Collapse
 
jon49 profile image
Jon Nyman

The main place I use it nowadays is in the console. If you like to redeclare variables I don't think you can do that with let. So, there is at least one very good place to use var!

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
 
yamanidev profile image
Mohamed Yamani

As soon as I read the title, I didn't give a damn if it was a clickbait or not, I am reading this anyway xD. I like the humor, keep it up!

Collapse
 
thumbone profile image
Bernd Wechner

Love the faux title ... ;-)

Collapse
 
fyodorio profile image
Fyodor

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

Collapse
 
posandu profile image
Posandu
const r = "Sad";
let reaction = r;
Enter fullscreen mode Exit fullscreen mode
Collapse
 
dominuskelvin profile image
Kelvin Omereshone

If you know the why, you can live any how.
— Friedrich Nietzsche

Collapse
 
gitcommitshow profile image
gitcommitshow

You're redefining the click-bait. Nice article.

Collapse
 
gab profile image
Gabriel Magalhães dos Santos

don't underestimate var, it was the first global storage concept in javascript lol

Collapse
 
fmontone profile image
Fabio Montone • Edited

Yeah! Cool click -bait and I was fairly trapped! Was ready to vomit a fierce comment and let the community know how I'm sharp with JS!
🤣🤣🤣🤣🤣🤣🤪 Cheers!

Collapse
 
morewry profile image
Rhy Moore

What about hoisting?

Collapse
 
cnsknight profile image
Codename: Steeve Knight

Inexcusable lack of editing here. I could not get past the second paragraph!

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
 
peteole profile image
Ole Petersen

And next week: 3 reasons to use PHP!

Collapse
 
mleandrojr profile image
Marcos Leandro

I fell in the bait!
It's a great article.

Collapse
 
dovey21 profile image
Somtochukwu Nnaji

I was about to object my lord 🤣 till i got to the last. Well why do most tutorials still use it?