Search code examples
javascripterror-handlingscopetry-catchvar

Why isn't 'error' variable reassignment functionally scoped inside of catch{} block?


I am working with try-catch blocks in JavaScript and have run into some variable scoping behaviour I don't completely understand.

I understand that console.log(boo) prints 20 to the console because the variable has been declared with the var keyword and hence it is functionally scoped (i.e. not block scoped to the catch block).

However, I don't understand why the err variable isn't also scoped to the IIFE in the same way as the boo variable. Therefore I don't understand why it is undefined outside of the catch block.

(function() {
  try {
    throw new Error();
  } catch (err) {
    var err = 10;
    var boo = 20;
    console.log(err); //'10' (as I expect)
  }
  // Why doesn’t this log '10' ???
  console.log(err); // 'undefined' (but I expected '10')

  console.log(boo); // '20' (as I expect)
})();


Solution

  • I found the answer.

    It is because the exception 'identifier' (which is the 'err' variable in the example above) is not available after the catch block has finished executing. This seems like a special case of handling scoping in JS and is definitely a 'gotcha' until one does some digging.

    Hopefully this helps someone else!

    From the docs: enter image description here