Yes, but the point is that eventually you may want to work on code that other people may be working on. Or you may be working on a project big enough that you loose track of the scopes of various blocks. Yes,
var can be used responsibly, the problem is that it allows itself to be used irresponsibly. If you think you can keep yourself from using it irresponsibly and can keep track of what scope is where across all the code blocks in all the files in all your projects and you’ll never need to work with other coders, then I guess it’s fine. Otherwise,
let is a safer option. Having come from more stronly typed languages, I always thought
var was a little hinky. Types in general, in JS, are hinky.
It’s a bit overkill to say that var is bad - it was used for a long time after all, before better alternatives came along.
I’m not saying it’s bad, just less safe and a better option is available. It’s an improved tool, that is inline with how these things work in a lot of other advanced languages. Yes, it was used for a long time. But now a better, safer, less prone to mistakes option is available. The only “advantage” to
var is if you like being sloppy with you declare and scope variables. If you declare and scope them responsibly (in the right place, and in the proper scope) then they are essentially equivalent. Most languages would crash if you tried to declare variables the way
var let’t you get away with. I think enforcing good planning and practices is a good thing. Again, I can find no real advantage to
I hope you meant variable hoisting, not function hoisting. Function hoisting is great!
Hoisting is a byproduct of the two-pass compilation that JS interpreters do. It was not a “feature” built into the language with purpose, afaik. Again, I think it is bad practice to rely on hoisting. Ideally, things should be declared at the top. Although I will admit that sometimes I move my helper functions to the bottom of the page for clarity. But other languages get by just fine without this. And if I wanted, I could just put them in their own file.
But in general, relying on the broad scoping of
var and the sloppiness allowed by hoisting are not good and often the result of bad planning. They solve no problem that can’t be handled with good practices. All they do is open you up to possible errors or cryptic code. A quick check shows that that seems to be the general consensus.