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 JavaScript Basics (Retired) Creating Reusable Code with Functions Variable Scope

Isn't there times when what you want exactly is to override the global scope?

In the video, he says that it's best to initialise a variable to make it "local" so to speak, in each function. Basically, that I should always declare variables inside functions using the keyword var. But there's times when we actually could /want/ to override an existing variable in the global scope, right? For example, photo galleries, where you could want to advance or go back by a number, depending on where you are.

I may have answered myself, but I still want to be 100% sure. Is this is a rule set in stone? Is there a reason I may want to actually do this everytime?

1 Answer

Steven Parker
Steven Parker
229,744 Points

Yes, it's possible that a function might access global variables, and in that case there would be no declaration of that variable within the function.

But when possible, "best practice" would be to handle communication in or out of a function using arguments and return values. This makes it much easier to someone reading the code to understand what a function does while reading the code near where it is called.

What if you are accessing an object or array in that function? If the array is specific to that function should you move it inside the function or is it ok to leave the array global?

Steven Parker
Steven Parker
229,744 Points

Recommended "best practice" is to locate any variables, including arrays, that are used exclusively by a function so their scope is limited to that function.