The ES5 language spec clearly states that Error(foo)
does the same thing as new Error(foo)
.
But I notice that in the wild, the longer new Error(foo)
form is much more common.
Is there some reason for this?
Is there any situation where using new Error(foo)
is preferable to using Error(foo)
?
new Error('message') captures the execution stack + others Using an Error object allows you to capture the execution stack at the point where you throw the error. So when the error gets passed up the error handling tree, so does this stack snapshot.
The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.
The try statement allows you to define a block of code to be tested for errors while it is being executed. The catch statement allows you to define a block of code to be executed, if an error occurs in the try block.
There are three main types of errors that can occur while compiling a JavaScript program: syntax errors, runtime errors, and logical errors.
Is there some reason for this?
It's simply the habit of always calling constructors with new
. Consistency rules!
It's a good practice to do even when they work without new
, and recommended by several style guides and related tooling. Btw, since ES6 Error
is subclassible, and its subclasses will require new
.
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