Skip to content
Advertisement

How can I keep track of game data that is changing without using global variables? [webpack]

I had a simple Rock Paper Scissors game where I used global variables to keep track of game data like player score, computer score, the state of the game (ongoing = true/false), etc.

I recently learned how to use webpack so I bundled up my code into modules to practice in this format, and now I’m unable to access the variables or objects that I declare in my dist/index.js file.

I think I understand why I’m unable to access them, but my question is: how am I supposed to update the state of the game without that data being stored anywhere in memory? Or am I wrong, and is that data actually stored somewhere? If you could give me a high-level overview of how I would achieve this, or if there is some example code I can review that uses bundling, that would be nice.

Sorry if this is a newbie question, I tried Googling for hours and couldn’t find exactly what I was looking for.

Advertisement

Answer

There are quite a few ways to do this. One approach is to have a module that manages state that the whole project needs access to. You can have:

JavaScript

Whenever you need to set something, either import and call setState, or call getState and mutate the state.

JavaScript

Another approach is to, from somewhere around your entry point, continually pass down an object that’s shared among your app’s modules.

JavaScript

and then just access the state argument in those functions, and keep passing it down to other functions if needed.

JavaScript
JavaScript

Another way (which I wouldn’t recommend) would be to explicitly create a global variable:

JavaScript

But that defeats the purpose of using modules.

Advertisement