1

(function () {
  try {
    throw new Error();
  } catch (x) {
    var x = 1;
    var y = 2;
    console.log(x);
  }
  console.log(x);
  console.log(y);
})()

why does this code print: 1 undefined 2 Since we are using var to declare both x and y, why is x not accessible outside the catch block but y is.

Simone Rossaini
  • 8,115
  • 1
  • 13
  • 34
aryan singh
  • 374
  • 2
  • 9
  • You try to use `exception_var` with same name of variable, for example try to change `catch (x)` to `catch (error)` all work. – Simone Rossaini Aug 23 '21 at 11:50
  • Variables declared with `var` are hoisted to the top of the function, hence you can access them outside of the catch block. `var x = 1;` will modify the `x` parameter of `catch (x)`, not the declared `x` variable. – Ivar Aug 23 '21 at 11:51

1 Answers1

1

That's because x is the parametre variable of your catch catch (x). Thus you can't access it outside of it's scope. As when you're trying to change the value of that said variable, it's changing the parametre variable that isn't accessible outside.

If you try to change your x to z, it'll work :

(function() {
  try {
    throw new Error();
  } catch (z) {
    var x = 1;
    var y = 2;
    console.log(x);
  }
  console.log(x);
  console.log(y);
})()
Alexandre Elshobokshy
  • 10,720
  • 6
  • 27
  • 57
  • but i use the keyword var while declaring x again. Won't it redeclare the variable ? – aryan singh Aug 23 '21 at 11:54
  • You're still modifying the parameter `x`, you're not creating an entirely new variable in this instance. – Alexandre Elshobokshy Aug 23 '21 at 11:57
  • @aryansingh using `var` with an existing binding does either a) nothing at all b) causes an error if you try it with a variable that was declared with `let` or `const`. – VLAZ Aug 23 '21 at 12:05
  • if i don't use var, x , trying to access x outside the catch block throws error. But if i do use var to redeclare it, accessing it outside the catch block gives undefined meaning the variable was declared but not initialized. But why ? – aryan singh Aug 23 '21 at 12:08
  • @aryansingh Have you read the duplicates linked above your question? – Ivar Aug 23 '21 at 12:18
  • yeah, due to hoisting x, y are hoisted to the function level. If we use x for error parameter and redeclare using var x, what it dos it hoist the variable x. Catch block after running destroys the error parameter but x was hoisted already so, it's value becomes undefined. That's why accessing x, y outside the catch block gives undefined and 2. – aryan singh Aug 23 '21 at 12:28