throw Error('msg') vs throw new Error('msg')

JavascriptException

Javascript Problem Overview


var err1 = Error('message');
var err2 = new Error('message');

What's the difference? Looking at them in the chrome console, they look identical. Same properties on the object and the same __proto__ chain. Almost seems like Error acts like a factory.

Which one is correct and why?

Javascript Solutions


Solution 1 - Javascript

Both are fine; this is explicitly stated in the specification:

> ... Thus the function call Error(…) is equivalent to the object creation expression new Error(…) with the same arguments.

Solution 2 - Javascript

Error does act like a factory, like some other native constructors: Array, Object, etc. all check something like if (!(this instanceof Array)) { return new Array(arguments); }. (But note that String(x) and new String(x) are very different, and likewise for Number and Boolean.)

That said, in case of an error, it's not even required to throw an Error object... throw 'Bad things happened'; will work, too
You can even throw an object literal for debugging:

throw {message:"You've been a naughty boy",
       context: this,
       args: arguments,
       more:'More custom info here'};

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionIlia CholyView Question on Stackoverflow
Solution 1 - JavascriptpimvdbView Answer on Stackoverflow
Solution 2 - JavascriptElias Van OotegemView Answer on Stackoverflow