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 Getting Started With ES2015 Defining Variables With let and const Creating Unchanging Variables With const

Rebecca Palumbo
Rebecca Palumbo
5,506 Points

Shouldn't a constant variable be the same in the whole program and not be different in a function?

It seems like a constant should be consistently a constant. Is there a reason someone would use the same constant variable in a function, if it's already been defined outside the function? I don't understand why someone would do this.

1 Answer

Steven Parker
Steven Parker
228,991 Points

Variables in a function have a scope that pertains only to that function. If you create a variable that has the same name as a global one, it is said to "shadow" the global, and any reference to that name inside the function refers to the new one created in the function. The global remains unaffected when the function ends.

This is typically not done intentionally, but it is not uncommon in code that is created by multiple authors. The fact that separation of the two variables is handled cleanly is one of the strengths of the language.

For more details, see this Wikipedia page on Variable Shadowing.