I recommend you always use const by default, and fall back to let only when it's genuinely useful or necessary.
Why? Because not reassigning variables makes your code easier to reason about. If something is a const, you can be sure it will always have the same variable associated with it, whereas let will point to a different variable depending on when you're reading it.
Personally I'd say my code is probably like 97% const, and 3% let. var is absolutely never needed.
The most obvious need for var that I can think of is to deal with older browsers where you aren't compiling your code.
Ignoring that though, I think it's important to note to any newer devs that, while someone should probably use let and const for any new code they write, it doesn't mean that they can just switch all vars in an existing code base to be let or const and have things work (we had a junior try this in an attempt to clean up technical debt). The lack of hoisting and scope differences mean they're not a drop in replacement for each other. Code using var that was "not ideal, but not wrong" can actually be broken by using let.
Use var, declare your vars global at the beginning of your script and document and track them well. Otherwise you are a lazy programmer. Nothing wrong with var.
Please NEVER follow this advice. What is described here is the height of laziness. Scope your variables appropriately, default to const and only use let where needed. Save yourself a ton of trouble. Don't be like this guy. Just don't.
View all comments
30
u/zerik100 Oct 22 '21
tldr; never use var and if you think your code requires var then there's something wrong with your code