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

Philip Bessa
Philip Bessa
5,396 Points

Over-complicated? Why not rename a variable?

I know it's just meant to define and show what a scope is, but instead of leaving the code in the video like it was, why not just rename one of the variable names and avoid the issue in the first place?

That should have at least been pointed out. Why would you have two variables of the same name anyway? I was always told that's poor form.

2 Answers

It's a big help to be able to use as clearest a variable name as your can. Sometimes in a function we are just dealing with an array, and in another function, we're also dealing with an array. It would complicate things to have to say var arrayForThisPurpose in one function and var arrayForThatPurpose in another function just to make them unique in your program. It's just an variable to hold an array. That way you can also copy and paste useful function into multiple programs.

Within the scope, sure, you don't want to keep using a variable name for different purposes.

Dave McFarland
STAFF
Dave McFarland
Treehouse Teacher

Philip Bessa

Sometimes you don't have a choice for variable names. For example, if you're using other people's code or 3rd party library's like jQuery, you'll likely run into variables with the same name and you don't want to change those, because the library expects those exact variable names. However, because those variables live within the "scope" of their code -- for example within the jQuery function -- they won't collide with any global variables you might create.

And, as Dan Oswalt points out, you want to make sure your variable names are meaningful and accurate for the context in which they live. Because of the way scope works, you don't need to worry about using the same names as long as they live in separate functions (scopes.)

This is some really good information. I enjoyed this video because I feel I ran into bugs in programs in the past due to this very reason.