DEV Community

Discussion on: Stop using var for declaring variables !!!

 
chakudi profile image
Vaishali JS

To be honest, this whole topic is about personal opinion/preference of developers with respect to variable declaration.

I've been working with JS for many years and 3 of my major projects are still completely powered by ES5, and believe me, I never had issues reading or understanding code with var.

In my personal opinion, let is only giving some convenience at lexical level which is certainly useful in many cases, but it doesn't replace var if you see from perspective of JS engine.

Thread Thread
 
peerreynders profile image
peerreynders

The way var is hoisted is yet another unnecessarily confusing thing about it.

It's only confusing if you're pretending to work (or rather be working) in "some other language". That is simply how var works in JavaScript - the "hoisting" is a natural consequence of var being function or globally scoped. For consistency sake, style guidelines recommended to put all var declarations at the top of the function and to resist the urge to pretend as if var was block scoped.

Then they should (personal opinion) add a rule to their linter that disallows writing it in their own code.

Acknowledging the "personal opinion" qualifier here, however:

  • Beginners need to know the rules and follow them.
  • Intermediates need to know and understand the reasoning behind the rules.
  • Experts will follow the rules implicitly because they understand their value and will accommodate everybody else by documenting clearly why the rule doesn't apply in this particular scenario (this in itself should serve as enough of a dis-incentive to discourage overriding the rules casually).

From that perspective a warning that can be disabled locally seems more appropriate.

Thread Thread
 
lionelrowe profile image
lionel-rowe • Edited

a warning that can be disabled locally seems more appropriate.

"A warning that can be disabled locally" is exactly how eslint (and I think all common alternatives) already work.

// eslint-disable-next-line no-var
var x = 5
Enter fullscreen mode Exit fullscreen mode

For consistency sake, style guidelines recommended to put all var declarations at the top of the function and to resist the urge to pretend as if var was block scoped.

Thus removing any perceived advantage from using var in the first place.

Thread Thread
 
peerreynders profile image
peerreynders • Edited

Thus removing any perceived advantage from using var in the first place.

I somehow doubt that "hoisting" was ever seen as an advantage of var - it's simply an emergent property of how var was implemented by the runtime - one that needs to be taken into account.

try {
  // eslint-disable-next-line no-var
  var something = createSomething();
} finally {
  if (something) something.freeResources();
}
Enter fullscreen mode Exit fullscreen mode

The obvious intent here is to cross the block scope barrier but in doing so something is now available in the entire function scope which shouldn't be construed as an invitation to use something before or after try/finally.

let something;
try {
  something = createSomething();
} finally {
  if (something) something.freeResources();
}
Enter fullscreen mode Exit fullscreen mode

Has the advantage of not being assignable before the let but still exists past the try/finally.


PS: Personally I'd likely go this route:

function useSomething(consumeSomething) {
  let something;
  try {
    something = createSomething();
    consumeSomething(something);
  } finally {
    if (something) something.freeResources();
  }
}

// ... 
try {
  useSomething(consumer);
} catch(error) {
  // ...
}
Enter fullscreen mode Exit fullscreen mode

rendering the entire var vs. let discussion moot.

Thread Thread
 
_genjudev profile image
Larson

@Vaishali JS

And the amount of bugs have nothing to do with language features, in my experience. It depends on the developer's understanding of language.

What is that for a philosophy. Javascript has by far the most bugs writting I ever detected in any language. Because someone says you need to understand the language. No. You write an var at the end of the line is not understanding the language, is writing bad code.

Most of this because

  1. JS is often use in non critical projects
  2. you are not punished enough for errors because JS can run even if you get an error
    1. this is cool and shit
if(user) {
  console.log('Welcome, ' + user);
} else {
  console.log('Welcome, guest');
}

let user = 'Vaishali'; // assume that user name received from API response
Enter fullscreen mode Exit fullscreen mode

You done this? I hope not that is so fucking bad programming. Even when using var, declare it before you try to use it.

That's not an argument for var it's completely against it. Any developer watching your code needs first to be clear there is no var hidden in your function. And when you have big projects you don't want to do this. You want to have a clear view of functions. And don't want to read until the last line to be sure there was an var.

Thread Thread
 
peerreynders profile image
peerreynders

So this example is shit.

I didn't make it up - and crass language doesn't strengthen your argument.

I also don't believe hoisting of var was ever an actual, deliberate feature - it's simply an explanation (and name) of its behaviour given that it has function scope and can be declared anywhere within the function. Hoisting of function names on the other hand is quite deliberate because that way multiple functions can reference one another regardless of source order.

Javascript has by far the most bugs writting I ever detected in any language.

Are you talking about JavaScript or code written in JavaScript?

Lots of junior developers write code in JavaScript. Junior developers write "inexperienced" code in any language. And juniors not exploring other languages besides JavaScript probably have a hard time to improving their use of JavaScript.

JS is often use in non critical projects

It's also used in mission critical projects.
For example starting in 2014 eBay shifted from their Java-based stack to a Node.js-based stack - Marko which essentially runs their web front. - so what is your point?

you are not punished enough for errors because JS can run even if you get an error

Again forget about any expectations that you may have from some other language.
JavaScript's behaviour aligns with the web's resilience model. From the browser's point of view JavaScript is the least important aspect of any page it loads:

  1. Content is the foundation
  2. Markup is an enhancement
  3. Visual Design is an enhancement
  4. Interaction is an enhancement

JavaScript fails silently because the browser doesn't want to punish the end user for a developer's negligence of testing their code properly. This was in an attempt to preserve the information that could be conveyed by the content, markup and visual design.

It's client-side rendered SPA's which turned everything upside down. It's ironic that about the time the back end "discovered" microservices (2005-2011) the front end "discovered" monoliths in the form of SPA'a (2002-2003). Going by that MPAs should be coming back as the front end version of "microservices".

I'm personally not thrilled about Node.js being used in production on the back end - but it is. I'll also admit that JavaScript is far from the pit of success we would all like to have.

The problem with JavaScript is that it is deceptively easy to learn just a little bit of it; possibly operating on an erroneous mental model - but it actually takes quite a bit of effort to know JavaScript well enough to use it well.

Thread Thread
 
chakudi profile image
Vaishali JS • Edited

@larsonnn

What a vague comment is that!
I am myself using JS in a large missing critical project. We are a team of 20 JS develpers and we are using only ES5.

We have our own ways of achieving block scope using var and we have our own patterns for declaring globals!

Its definitely not about the language, its about the developers and the way they choose to use the language 😊

Thread Thread
 
_genjudev profile image
Larson • Edited

I was not answering you peerreynders
But here:

I didn't make it up - and crass language doesn't strengthen your argument.

I didn't say you did. The example is still a worst one. What you learn is, with var its not a problem if you code bad. And using var only that you can use it in finally or above your var statement is for me bad code. (Opinion here)

Are you talking about JavaScript or code written in JavaScript?

What's written in javascript ofc.

gain forget about any expectations that you may have from some other language.

You're right. That does not mean I need to accept the fact that var is for now. In my programs there is no var and I don't miss it. And I guess the most developers will not miss it if it's not available.

From the browser's point of view JavaScript is the least important aspect of any page it loads

in the 90s or early 00's yes. If you take v8 for example, it is clear that JavaScript is NOT the least important aspect. Also JS is one of the most used Languages. Or I didn't understand you here.

It's also used in mission critical projects.
For example starting in 2014 eBay shifted from their Java-based stack to a Node.js-based stack - Marko which essentially runs their web front. - so what is your point?

Ok fair. From the financial view. But do you wan't to run automated cars with javascript? Or Rockets to fly? Ofcourse not, it's fine. But that does not mean we should learn how to programm bad. And the language can support for writing easy safe code. And with node-js as your backend. I don't want some easy errors to make when it comes to writing Data in the Database. And we use so much microservices in JavaScript that we could raise the bar for what the language should have. If not, I don't see in the longrun JS only lose.

JavaScript is so quickly to mess up like no other language. And that's my whole point. Why sticking with var there is no use case. The only use cases presented was for hoisting. I don't see any other argument. Its not faster, its not saver. Its not intuitive to declare under the usage:

const fun= () => {
  if(true)
    var x = 2;
  console.log(x);

}
Enter fullscreen mode Exit fullscreen mode

Why should I do this? Its not intuitive. You would write more like this:

const fun = () => {
 let x; // or default value
 if(true) 
    x = 10;
 console.log(x);
}
Enter fullscreen mode Exit fullscreen mode

And that's just the worst example. Because you can write more elegant. But that's another topic.

I know that will not make JS the perfect language. And perfection will never be reached, because JS has many other things we could discuss.

Lots of junior developers write code in JavaScript. Junior developers write "inexperienced" code in any language. And juniors not exploring other languages besides JavaScript probably have a hard time to improving their use of JavaScript.

lots of junior developers write python or java code also. I see code from "experienced" developers which do the same misttakes. Or don't care and that's by far the worst.

It's client-side rendered SPA's which turned everything upside down. It's ironic that about the time the back end "discovered" microservices (2005-2011) the front end "discovered" monoliths in the form of SPA'a (2002-2003). Going by that MPAs should be coming back as the front end version of "microservices".

this will switch every time. That's normal. That's like haircuts. With nextjs or nuxtjs they just sell SSR as a new feature. (Yeah, it's a little more... But common).

[var, let] const is one statement to much.

Vaishali JS

Mar 7 • Edited on Mar 7
@larsonnn
What a vague comment is that!
I am myself using JS in a large missing critical project. We are a team of 20 JS develpers and we are using only ES5.
We have our own ways of achieving block scope using var and we have our own patterns for declaring globals!
Its definitely not about the language, its about the developers and the way they choose to use the language 😊

It's not about your project. And I don't care if you have 20000 JS developers. Its about the language. If you can't understand that the language can be better with more sense in it. I guess you live in your bubble.
Because you can use var and have 0 errors with it, does not mean its good to have var. And I don't care about ES5, it's old.

Thread Thread
 
chakudi profile image
Vaishali JS • Edited

No language is good or bad in its own. Its only the way developers understand and use it.

Edit:
Just to add, ES5 is certainly old but most developers are not relying on ES6 unless they have babel/webpack or other third party tools to transpile ES6 into something that browsers care about.