Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When is `new Error()` better than `Error()`?

Tags:

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)?

like image 470
joeytwiddle Avatar asked Aug 04 '16 05:08

joeytwiddle


People also ask

What does New error do?

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.

Does throwing a new error stop execution?

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.

When to use try and catch JavaScript?

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.

What are the different types of errors in JavaScript?

There are three main types of errors that can occur while compiling a JavaScript program: syntax errors, runtime errors, and logical errors.


1 Answers

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.

like image 86
Bergi Avatar answered Sep 19 '22 13:09

Bergi