Global Variables For Web Development

I want to create 3D graphics which are interactive through widgets like sliders on a site. I want the graphics and widgets to interact with one another across different functions, so I would like to use the window class in JavaScript to make them global. I understand it’s generally bad practice to use global variables. However, I don’t really foresee it leading to confusion. What potential issues could arise if I do this?

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.

1 Like

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:

  1. You overwrite an internal global variable
  2. You create a global variable that overwrites a future global variable in the browser
  3. You overwrite your own global variables you wrote earlier
  4. You overwrite global variable within any external libraries you might end up using
  5. Your global variable gets overwritten by an external library you might end up using
  6. 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.