What is ‘variable shadowing’ and why it should be avoided.
Before we go straight to the definition, it is important to observe that a more comprehensive understanding of variable shadowing requires knowledge of two other fundamental programming concepts. Firstly, the importance of naming variables and, secondly, local variables and scoping rules.
What is ‘variable shadowing’? Variable shadowing occurs when a variable of an inner scope is defined with the same name as a variable in the outer scope. In the inner scope, both variables’ scope overlap.
According to variable scoping rules, the inner scope should always be able to access a variable defined in the outer scope, but in practice, shadowing will prevent that from happening. Let’s look at these two examples: