Skip to content
Advertisement

What is the difference between throw Error(error) and throw error

What is the difference between:

JavaScript

and

JavaScript

Also

Is the second one necessary? It seems like you are just wrapping an error with an Error Object. Which one is preferred? Please help me understand.

Advertisement

Answer

It’s possible that the value that the Promise rejected with was not an error object, but something else:

JavaScript

Doing

JavaScript

makes sure that the value being thrown is definitely an Error object, which could be important if the thrown value is examined later and is expected to be such an object. You wouldn’t want, for example, for undefined or null to be thrown (strange, I know, but not impossible) and for accessing a property of that to then throw at the point where you’re catching for real.

JavaScript
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement