DEV Community

Discussion on: 3 reasons to use 'var' in JavaScript

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.