0

Can someone please explain the output of the following function?

(function() {
  try {
    throw new Error();
  } catch (err) {
    console.log(err);
    var err = 5;
    var boo = 10;
    console.log(err);
  }
  //Guess what the output is here:
  console.log(err);
  console.log(boo);
})();

It console logs: 5 undefined 10 (in that order). However, I don't understand where the undefined is coming from.

deceze
  • 491,798
  • 79
  • 706
  • 853
  • *Variable hoisting* – Rayon Apr 03 '20 at 10:17
  • @deceze - Few may get confused by `console.log(err);` being `undefined`. – Rayon Apr 03 '20 at 10:21
  • 5
    The scope of `err` is only in the `catch` block. However, you happen to have a `var err` in there as well which hoists the name `err` to function scope, which prevents a name error in the outer block; but the `err` from inside the `catch` is still only valid inside the `catch`. – deceze Apr 03 '20 at 10:21
  • when you throw err it will catch it and log it. Since the error object, it empty first log is an empty object. Next, we assign 2 variables to err and boo to 5 and 10 respectively. so the second log is 5. now with the last 2 lines, I'm not entirely sure. They seem to be out of scope hence the log err is undefined. Not sure how log boo returns 10 even though it's out of scope. – Y4glory Apr 03 '20 at 10:24
  • @deceze I saw the linked dupe but I don't think it actually answers what happens here concretely. – VLAZ Apr 03 '20 at 10:25
  • @deceze ah, the other dupe is perfect. I was sure we had something along those lines and did try to find it but failed. Very well done! – VLAZ Apr 03 '20 at 12:13

0 Answers0