I am having troubles understanding this paragraph:
Declare all local variables with either
const
orlet
. Use const by default, unless a variable needs to be reassigned. Thevar
keyword must not be used
Could someone please explain what this means? Why shouldn't I use the 'var' keyword?
Those conventions are assuming ES2015 and above, which have
let
andconst
, which can be used to replacevar
. They're saying don't usevar
anymore, because thelet
andconst
semantics are more useful (according to those conventions [and my own personal opinion, not that that matters]).So for example, they're saying don't do this:
instead, either do this:
or this (but note that performance will be slightly slower with this last version, not that it usually matters1):
Similarly, if you're using a variable whose value will never change, use
const
:We can use
const
there because the value ofdate
never changes (just the state of the object it refers to).If you're anything like me, when you put these into practice (I don't follow those conventions, but I do follow this specific example of using
let
andconst
), if you're using other good practices (like keeping functions small, etc.), you'll be surprised at just how often you useconst
rather thanlet
because you end up with a lot of "variables" whose values you never want to change.1 You may be wondering why there's a performance difference between
and
The reason is that in the second one, a new
i
variable is created for every loop iteration. We can see that if we create a closure inside the loop:Again, the performance difference almost never matters (and will get smaller as engines get better at optimizing it out when they can), and lots of times you want the behavior of the second form (which is why it's defined that way). But it's there.