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)
?
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)
?
- 3 There could be static code checks considering uppercase function names classes and checking that they must be called with new. – Ingo Bürk Commented Aug 4, 2016 at 6: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 Commented Aug 4, 2016 at 6:14
1 Answer
Reset to default 26Is 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
.