JavaScript and Vars

It is what @r1chard5mith says, but also that programs that depend on global variables are often extremely hard to reason about - if you have variables that are in your program, and the values of those variables can be modified, then you’re likely going to need to know what their values are at any given time to successfully write/debug your program. That’s not feasible beyond absolutely trivial programs, so you tend to get wierd, hard to debug errors.

As an example, one thing that comes up over and over on FCC is people using global variables in the algorithm challenges. So the programs may be totally correct, and will work when people test them in isolation. But the issue arises that all the tests past the first fail. First test passes, but a global value is modified. Then the next test, instead of starting with a clean slate, starts with this globally-set value, modifies it. Then the next test starts with the newly-modified value and so on.

There are times when they are useful, but often the best way to use them is to keep them in a specific place, behind an interface. As an example, if you encounter Redux, that works by just keeping the entire state in a single object that you can only access/update in a very specific way. But [the interface to] that object needs to be accessible to your entire program.


Also, the two newer variable keywords, const and let are there to replace var (which cannot be deprecated or have how it works be changed), to prevent some of the issues with it that you kinda touch on in your first question. const is the more useful of the two; it has to be assigned a value in initialisation, and cannot be redeclared or rebound within a scope.