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!
You're right that var
is function scoped and not block scoped, however there's an exception for catch blocks if the var
declaration has the same name as a catch block bound variable such that the shadowed var
declaration will not be lifted to the function scope.
Relevant piece of the spec: https://262.ecma-international.org/10.0/#prod-annexB-CatchParameter
The Block of a Catch clause may contain var declarations that bind a name that is also bound by the CatchParameter. At runtime, such bindings are instantiated in the VariableDeclarationEnvironment. They do not shadow the same-named bindings introduced by the CatchParameter and hence the Initializer for such var declarations will assign to the corresponding catch parameter rather than the var binding.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With