JavaScript Getting Started With ES2015 Defining Variables With let and const Creating Unchanging Variables With const

Rebecca Palumbo
Rebecca Palumbo
5,369 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
177,563 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.