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 Loops, Arrays and Objects Simplify Repetitive Tasks with Loops A Closer Look at Loop Conditions

Seth Roope
Seth Roope
6,471 Points

So he declares a global variable and then passes it through the function as a parameter. Is that not frowned upon?

I don't know why but seems like this could cause issues. Even if there are no issues is this best practice?

1 Answer

Steven Parker
Steven Parker
229,788 Points

There's nothing wrong with passing global variables.

This is especially true if you're calling the function from code in the global scope.

Now what might be a questionable practice is for a function to make use of global variables that are not passed as arguments.

Seth Roope
Seth Roope
6,471 Points

Oh good cause I was wanting to do that earlier but it just didn't seem right in my mind for some reason.

I don't see the issue with using a global variable within a function that doesn't get it passed as an argument though... Can't think of an example but I would think you might have several functions making use of a global variable at some point. Is there an issue that can arise or just a better way to do things?

Steven Parker
Steven Parker
229,788 Points

Best practice functions are reusable and maintainable.

To make a function easily reusable in other program environments, it should not rely on anything not passed to it or privately maintained internally. Also, in large programs, it can be easy to forget what relies on certain global values and changes might be made at a later time in the outer program that would impact the function's ability to operate.

I admit that neither of these concerns may seem important in a small program, but they are good habits to develop.

Seth Roope
Seth Roope
6,471 Points

OK, that definitely makes sense. I am trying not to pick up any bad habits early on. Thanks for your input.