loading...

Do You Still Use Var? If So Why?

gabrielwebb profile image Gabriel Webb ・1 min read

Is using the keyword var still viable in 2019/2020? What’s your use case for it? Is it only for older legacy code?

Discussion

pic
Editor guide
 

Am I the only one who thinks const should be the only thing used?

 
[deleted]
 

I would like to note that const doesn't provide imutability, it only protects against reassignment

Ofcourse, const isn't enough, but it's a starting point

[deleted]

I'd argue you shouldn't add props to an object after you create it

 

I'd argue you should never have any value change (not in the foo = bar sense of change)

 

I am genuinely interested in your thoughts here

 

I use it. At the very least is useful for this kind of thing.

try {
  var stuff = await unsafe_stuff();
} catch (err) {
  return Promise.reject(err.message);
}
 

Why is it necessary to use var instead of let in your example? You don't access stuff variable in catch block anyway.

 

But I want to use it outside the try/catch block.

Just define it in the parent scope. It has extra line if compare with var, but I think this code is more obvious, because there is no implicit hoisting.

async function foo() {
  let stuff;
  try {
    stuff = await unsafe_stuff();
  } catch (err) {
    return Promise.reject(err.message);
  }
  console.log(stuff);
}

That is what I'm trying to avoid. And you could still do the same with var.

I choose to believe var's implicit hoisting is a feature and not a bug.

I agree, this is a valid use case for var if you prefer implicit hoisting.

 

I use var in devtools console, because with let/const I got Uncaught SyntaxError: Identifier 'foo' has already been declared when re-declaring a variable.

 

I use var out of habit when I'm typing something out real quick.

My older projects use so many vars.

 

I use var in console only, It lets me redefine and assign new value :P

 

I wanted to switch, but last I ran benchmarks against it, let ran considerable slower than var.

I'll test it again after the new year.

 
[deleted]
 

Negative. Clearly measurable differences in a highly optimized environment where performance is highly critical.

*** For fun, just did some performance testing. Right now I see no notable difference in performance between let and var. Yay, because I want to use let everywhere =)

 

Yes, I use it. Like, why wouldn't I?

 

Great run-through in this StackOverflow answer. They behave differently, it's important to know what the differences are. I find let clearer in almost every case, the only exception in my personal use has already been covered by other commenters - the try/catch thing doesn't really have a clean workaround using let.