throw Error('msg') vs throw new Error('msg')
Asked Answered
T

2

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

Tyrosine answered 8/11, 2012 at 17:42 Comment(2)
All the native constructors are defined in ECMAScript, including their respective behavior when invoked without new.Bridgers
See also When is new Error() better than Error()?Conjecture
F
241

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.

Fulbert answered 8/11, 2012 at 17:43 Comment(3)
Is this true in ES6 as well?Kilter
Yes. For current docs see: ecma-international.org/ecma-262/6.0/…Lunt
@Kilter - Yes. Backward compatibility is TC39's highest priority. The mantra is "don't break the web."Abey
T
25

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'};
Tilsit answered 8/11, 2012 at 17:46 Comment(7)
I'm afraid I don't fully agree. String("abc") does not create a String object, whereas new String("abc") does.Fulbert
@pimvdb: true, I've changed it to Object => Object('foo') returns a string object... come to thing of it almost all native constructors is a bit wrong... Number, Boolean,Date,String all don't...Array, Object and Error do, but Event and all DOMxxxx-api constructors throw errorsTilsit
I also think new Array(arguments) does not do exactly what Array(1, 2, 3) does. But probably I'm just nitpicking :)Fulbert
@pimvdb: It probably doesn't, no. Then again: I always advise against the use of new Array(), for obvious reasonsTilsit
Complementary with regard to throwing strings: A string is not an errorCornhusk
@alex: Granted, throwing non-Error instances (or string literals) looses the stack-trace. Just a nit-pick on the linked article: arguments.callee is forbidden in strict modeTilsit
“You can even throw an object literal for debugging” — or simply use debugger; or console.trace.Edgell

© 2022 - 2024 — McMap. All rights reserved.