If the initializer of a const or let variable throws an error, accessing that variable throws a ReferenceError -- even when checking its type via typeof.
// Foo.js
class Foo { constructor() { /* Something goes wrong and throws... */ } }
const gFoo = new Foo(); // Throws an error
// Elsewhere...
console.log(typeof gFoo); // throws ReferenceError: foo is not defined
Is there another way to test whether gFoo was successfully initialized, or do I have to wrap a typeof check in a try/catch block?
let isInitialized = false;
try {
if (typeof foo != 'undefined')
isInitialized = true;
} catch (e) {} // ugly but it works
Mainly, I'm surprised that typeof can throw a ReferenceError.
When an error is thrown, the execution of the current function stops (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. At that point, the variable doesn't get initialised, causing the ReferenceError exception.
So to answer your question, whenever you know there are possible errors thrown, make sure to always wrap it within try catch blocks.
With your case above, since the error could happen within the function assigned to foo, you should have the try catch block there; Something like:
const foo = (() => {
try {
// Do whatever
throw Error();
// return value to assign to foo
} catch(err) {
// Log error for monitoring
// return undefined
}
})();
if (foo) {
// Do something with foo
} else {
// Do something if foo errored
}