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 Tracking Data Using Objects The Student Record Search Challenge Solution

Why do not declare report variable as global?

Hi guys,

what happens if I declare the report variable as global?

What is the purpose of declaring it as local variable?

Would it be wrong to declare it as global?

Thanks!

1 Answer

Steven Parker
Steven Parker
231,007 Points

A major reason for local variables is that you get a new one each time you call the function. This enables the concept of recursion, where a function might call itself (with modified arguments) to do a portion of the overall task. Each call has a "private version" of the variable to use without altering the one in the caller. If only global variables were used, recursion would not be possible because all calls would share the same variable.

Another reason for keeping variables local is to make the code easier to maintain. Global variables can be modified by inline code or other functions, but local ones cannot. This limitation is called variable scope. In a perfect program (where recursion is not used), global or local would not make a difference. But the more global variables are used when local ones will do, the more opportunities there are to have problems later.