DEV Community

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

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.