However, I don’t really foresee it leading to confusion.
“I don’t foresee any problems, this should go smoothly.”
- George Armstrong Custer
The point is that as apps get larger, it gets harder to keep track of global variables and harder keep track of what is changing/consuming them and harder to write testable pure functions.
Sure, you can hold your car bumper on with duct tape and baling wire, but it might be indicative of a larger problem. Sure, it works, but it might be better to learn the right way to do it.
I would want to create some kind of a module to isolate these variables.
I honestly did not know what modules were, but it seems like it would be useful for my application so thank you! I found this example module as reference.
Let’s say I have a slider which I want modify a graphic, say a box. The slider has a bind function associated with it which is run whenever the slider is toggled. This function would modify the box.
I’m guessing I should write a module which exports the box. Inside the bind function this graphic could then be imported and then modified.
However, I’m not sure if the module would have a property which is the box using “let” or a function which creates the box. If I import the module from multiple locations, would they all refer to the same box?
A few reasons I can think of off the top of my head are:
- You overwrite an internal global variable
- You create a global variable that overwrites a future global variable in the browser
- You overwrite your own global variables you wrote earlier
- You overwrite global variable within any external libraries you might end up using
- Your global variable gets overwritten by an external library you might end up using
- Global variables could be a “code smell” of your code getting messy.
There are a number of patterns to not create global variables. You linked one above. Others such as using a top-level IIFE, or using a framework, or just using normal variable.
Generally the more complex of an application your building the more considerations you should make with your code. Otherwise as complexity grows, your code becomes harder and harder to maintain.