How do I get around using global variables?
Posted: Wed Dec 01, 2021 11:34 am
I'm having a little trouble understanding how I should be avoiding using global variables. For example, in one assignment I'm working on I made a function called buildDeck() which returns an array of 52 card objects.
What would be the best way to store this new array so that I can run other functions on it later, if I'm not "supposed" to be assigning that array to a global cards[] variable that I declared before running the function (which is what I'm doing now)?
I can understand that if I just needed to use the array once I could just use the return from the function, but I can't think of any approach other than storing the active cards that are in play into a global array, since obviously I can't keep using buildDeck() again once the game has started... Is there some big detail that I'm missing or something? I'm pretty new to this but I've read that it's bad practice to have global variables, and I'd really like to know I'm doing things the right way.
What would be the best way to store this new array so that I can run other functions on it later, if I'm not "supposed" to be assigning that array to a global cards[] variable that I declared before running the function (which is what I'm doing now)?
I can understand that if I just needed to use the array once I could just use the return from the function, but I can't think of any approach other than storing the active cards that are in play into a global array, since obviously I can't keep using buildDeck() again once the game has started... Is there some big detail that I'm missing or something? I'm pretty new to this but I've read that it's bad practice to have global variables, and I'd really like to know I'm doing things the right way.