Variable Shadowing in JavaScript


Variable shadowing in JavaScript occurs when a variable declared within a certain scope has the same name as a variable declared in an outer scope. This can lead to unexpected behavior and bugs in the code.

For example:

let x = 10;

function foo() {
  let x = 5;
  console.log(x); // Output: 5
}

foo();

console.log(x); // Output: 10

In the above code, the variable x is declared twice - once in the global scope and once within the foo function. When foo is called, it logs the value of the inner x variable, which is 5. However, when console.log(x) is called outside of the foo function, it logs the value of the outer x variable, which is 10.

To avoid variable shadowing, it is recommended to use unique variable names within each scope. If a variable with the same name as an outer variable is needed within a certain scope, it can be prefixed with an underscore or another identifier to differentiate it from the outer variable.

Another way to avoid variable shadowing is to use the let and const keywords instead of var. let and const have block scope, which means that variables declared with these keywords are only accessible within the block they are declared in. This can help prevent accidental variable shadowing.

For example:

let x = 10;

function foo() {
  if (true) {
    let x = 5;
    console.log(x); // Output: 5
  }
  console.log(x); // Output: 10
}

foo();

console.log(x); // Output: 10

In the above code, the inner x variable is declared within a block (the if statement), so it is only accessible within that block. When console.log(x) is called within the if block, it logs the value of the inner x variable, which is 5. When console.log(x) is called outside of the if block, it logs the value of the outer x variable, which is 10.



About the author

William Pham is the Admin and primary author of Howto-Code.com. With over 10 years of experience in programming. William Pham is fluent in several programming languages, including Python, PHP, JavaScript, Java, C++.