Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Leandro Severino
Leandro Severino
12,674 Points

when to use global variables?

I understand that declaring variables as locally as possible is good practice but what if we are caching DOM elements? Would it be better if I declare and define messageArea globally or would the pros of code organization outweigh the performance benefits? Just wanted to know your thoughts about it.

function showMessage(text){

let messageArea = document.getElementsByClassName('message')[0];
 messageArea.textContent = "";

}

1 Answer

Eric M
Eric M
11,545 Points

Well in this case you can always call getElementsByClassName again within whatever function needs it.

For a larger program the nodes getElementsByClassName stored in your global might not be valid later on if there are other functions changing the DOM heavily in between you storing it and retrieving it. And if you're calling it every time you need it then it might as well get called locally to the function that's actually using it.

There are times when it's fine to use a global variable. The short answer is "use them when they are only absolutely necessary" as you become more experienced you can go by "use them when they are the most elegant solution" but we can tend to consider them the best solution when they really aren't, which is why it's most often advised to avoid them.