Can I completely stop using var?

  • A+
Category:Languages

I'm taking a Java course and all declarations use block scope( int, double, boolean, etc.). In JavaScript however var is function scope.

let came along in ES6 and gave JS developers block scope. I'm adjusting my coding style and am opting to get rid of var all together.

Is this O.K.?


Is this O.K.?

Mostly; possibly entirely. There are very few situations where you would want to use var instead of let/const for technical (rather than style) reasons:

  • If you want to declare a global variable that becomes a property of the global object (global let, const, and class create globals, but they don't become properties of the global object).

    Of course, you could use this.varName = ... instead of var varName, since this at global scope¹ is the global object.

  • If you want to have several files where any of them may be the "first" (but not last) to define the same global, as is common in older module formats, e.g.:

    var MyApp = MyApp || {}; MyApp.something = /*...*/; 

    That works because the var MyApp part is silently ignored if MyApp is already declared; the equivalent structure with let would fail because it cannot be used if the identifier is already declared in the current scope.

    Of course, you're probably using a new module format by now. :-) And if you aren't, again you could do

    this.MyApp = this.MyApp || {}; MyApp.something = /*...*/; 

    at global scope.¹

[There used to be a minor performance benefit to using var instead of let in a function where it was used as a loop counter. Recent versions of modern browsers all-but-remove that minor benefit (and it was minor anyway).]


¹ Note that top-level code in a module (ES2015 module, Node.js module, most bundlers...) is not at global scope. It's at module scope. Also note that at the top level of an ES2015 module, this has the value undefined.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: