21

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

joeytwiddle
  • 29,306
  • 13
  • 121
  • 110
  • 3
    There could be static code checks considering uppercase function names classes and checking that they must be called with new. – Ingo Bürk Aug 04 '16 at 06:11
  • 1
    Another reason is people not knowing or knowing but preferring it because that's what they're used to given that using new has been the standard pattern. – Ingo Bürk Aug 04 '16 at 06:14

1 Answers1

25

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.

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • It looks like subclasses could implement the same behaviour if they wanted to, but there is no requirement for them to do so. That suggests it would be good practice to construct custom error objects using `new` and therefore it might be desirable to also construct standard error objects using `new`, for consistency. – joeytwiddle Aug 04 '16 at 07:28
  • 6
    @joeytwiddle Actually, `class X extends Error` [cannot implement the same behaviour](http://stackoverflow.com/a/31789308/1048572), it always throws when a constructor is called without `new`. – Bergi Aug 04 '16 at 07:33