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

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

What's the difference? Looking at them in the chrome console, they look the same. The same properties on the object and in the same __proto__ chain. It almost looks like Error acts like a factory.

Which one is correct and why?

+137
javascript exception
Nov 08
source share
2 answers

Both are good; This is explicitly stated in the specification :

... Thus, the call to the Error(…) function is equivalent to the expression for creating the new Error(…) object with the same arguments.

+132
Nov 08 '12 at 17:43
source share

Error acts like a factory, like some other native constructors: Array , Object , etc., Everyone checks for something like if (!(this instanceof Array)) { return new Array(arguments); } if (!(this instanceof Array)) { return new Array(arguments); } if (!(this instanceof Array)) { return new Array(arguments); } if (!(this instanceof Array)) { return new Array(arguments); } (But note that String(x) and new String(x) very different, as well as for Number and Boolean .)

However, in the event of an error, it is not even necessary to throw the 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'}; 
+15
Nov 08
source share



All Articles