This code is part of a javascript course I am doing. And this exercise was in the error handling part where I needed to guess the output.
Code:
(function () {
try {
throw new Error();
} catch (err) {
var err = 5; //creating another local err variable
var boo = 10;
console.log(err);
}
console.log(err);
console.log(boo);
})();
Output:
5
undefined //I don't understand this part
10
The error is passed as a parameter err in the catch block. But with var, the err variable gets overwritten. So instead of logging the error, 5 gets logged in the first console.log(err).
But I couldn't figure out why the second console.log(err) outputs undefined. As far as I understood, var is not block-scoped, so, inside the same function scope, I should have access to the err variable. And, due to hoisting, var becomes undefined initially. But as try/catch block is synchronous and I am logging the variable after defining it, shouldn't it log 5? Because console.log(boo) returned 10 as expected.
Is it due to creating the variable with the same name as the local parameter?
NB: This is my first question on stackoverflow. So forgive any mistake!