mrmagooey mrmagooey - 2 months ago 20
Javascript Question

Const behaviour if require fails

Opening the node repl (v6.6.0) and doing:

> const test = require('somethingGuaranteedToFail');
Error: Cannot find module 'somethingGuaranteedToFail'


Now the variable
test
can neither be redefined, nor has it been properly initialized.

> console.log(typeof test);
ReferenceError: test is not defined
> const test = 1;
TypeError: Identifier 'test' has already been declared


It seems to happen with anything that throws an error during assignment, not just require.

I guess the question is, is this expected behaviour? I would have thought the const variable would at least contain the
Error
object.

Answer

I guess the question is, is this expected behaviour?

Yes. A const cannot be redefined or redeclared. const test declared it, but failed to define it because an error was raised.

I would have thought the const variable would at least contain the Error object.

require does not return an error, it throws one. If you want it, you need to catch it.

Comments