-6

Understanding variable scopes

const { response } = somecall();
if (response) {
   const { response } = someOtherCallThatReturnsUndefined(response);
   // the value of response being passed in to **someOtherCallThatReturnsUndefined** is actually undefined
}
Free Lancer
  • 1,000
  • 2
  • 16
  • 33

2 Answers2

2

What you're doing is called variable shadowing.

When you declare a variable with const (or let) it's block-scoped: the second time you're declaring a new response constant you're in a different scope, so they're different variables. But the fact that they shares the same name, means you're shadowing the outer one (that could potentially lead to bugs); and preventing the inner scope to access to the variable of the outer scope.

To be clear:

  const foo = "1";
  {
     const foo = "bar";
     console.log(foo); // "bar"
  }
  console.log(foo); // "1";

The variable foo in the inner block is a totally different variable than the foo in the outer block, in fact when you exit the block you still have the right value. They just "shares" the same name, that's it.

ZER0
  • 24,846
  • 5
  • 51
  • 54
1

By saying const { response } you are declaring the variable in a different context than the original variable hence why you can do so.

Dylan
  • 2,161
  • 2
  • 27
  • 51