Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

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
215,372 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.