In the case of a simple change of var
to const
in Javascript, this conflicts with the author's intent.
At the end of the day, var
and const
do not have the same semantics. In modern Javascript, you use const foo
to declare a constant (no changes permitted), and let foo
to declare a mutable variable. var
is the older way of declaring a variable, and it makes no distinction about the mutability of the variable being declared. var
can still be used in modern Javascript, though it is recommended practice to use either let
or const
to indicate the mutability of the variable. In addition to mutability, different scoping rules apply to var
than to let
and const
.
Therefore, I'd argue that changing the way the variable is declared conflicts with the author's intent and should have been rejected:
var
is not semantically equivalent to const
mutability rules differ
scoping differs
var
is still valid, though no longer the only or necessarily encouraged way to declare variables
The original answer, as written with var
works. It's valid Javascript; if you run it as originally written it would work today in 2023 as it did when originally written in 2014.
---
I would even argue that a modern answer may still be written with var
: it makes no assumption about the required mutability of this declared variable in the greater scope of the original poster's application.
var
is not deprecated nor obsolete. It's fully compatible with ES6, you can use it without problems, there is no mention of "you should use const / let" anywhere on MDN: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…var
,let
andconst
for no reason, or uses exclusivelyvar
even though it's transpiled, would have a huge code smell/red flag to any experienced JS dev.var
never needs to be used any longer, except possibly in browser-compatible legacy code that isn't transpiled, which is very rare, or trivial throwaway userscripts and bookmarklets. ESLint, no varvar
here (though I think its a bad idea), I just thought in the majority of instances in which someone would copy-paste,const
would make more sense, and I thought if the OP answered today, they would probably useconst
. In any case, I want to learn, and if this was not the right move, by all means reject the edit.