DEV Community

Etamar
Etamar

Posted on

"Globally" speaking

Only after I finished my first JavaScript project for school I realize that I need to use Global Variables as less as possible.
Think about it, You have a pretty good file of code that you really want to keep tight and clean with a lot of functions that uses the same element more than once, So you the first thing that came to my head as beginner is to grab all the elements that are being used more than once and put them all at the beginning of the page stacked in a nice section.

Alt Text

So I guess I was wrong, I noticed that having so many Global Variables is not that good for two reasons..
The first reason is pretty simple, My cohort leader told me so :)
The second reason is that I noticed it is better to grab the elements individually in each function its being used.

Alt Text

There is a tricky part to this way of thinking,
I think that using Global Variables is very good but my recommendation of using it will be that is to check how many times you using a certain Variable for example...
If you using an element just a couple of times in my opinion it should not be in the global scope because you want to keep you Global Variables bank tight and efficient as much as possible.
But if you using a specific element A-LOT (let’s say at least 4-5 times) that is when it should be in the Global Variables bank.
Also we need to be carful because it is very easy to overwrite a window element or a function when we use Global Variables.

I hope this post help you choose the right way of using Global Variables,
Good luck with your code.

Top comments (0)