JavaScript interview question

What is variable shadowing in javascript?

Answer

Variable shadowing occurs when a variable declared within a certain scope (decision block, method, or inner class) has the same name as a variable declared in an outer scope. This outer variable is said to be shadowed.

If there is a variable in the global scope, and you'd like to create a variable with the same name in a function. The variable in the inner scope will temporarily shadow the variable in the outer scope.

Example:

/**
 * Variable Shadowing
 */
var val = 10;

function Hoist(val) {
  console.log(val);
}
Hoist(20); // 20

More Technical Interview Topics