4

try {
  throw new Error();
} catch (x) {
  var x = 100,
    y = 10;
  console.log(x);
  console.log(y);
}
console.log(x);
console.log(y);

The above code gives the output

100
10
undefined
10

Can anyone please help me understand why the value of x is undefined outside try-catch, but y is 10.

If I change the catch variable from x to some other random name the output comes as expected. i.e:

try {
  throw new Error();
} catch (x) {
  var foo = 100,
    y = 10;
  console.log(foo);
  console.log(y);
}
console.log(foo);
console.log(y);
100
10
100
10
Michael M.
  • 10,486
  • 9
  • 18
  • 34

0 Answers0