Is `RegExp(…)` really equivalent to `new RegExp(…)`?

According to §22.2.4 The RegExp Constructor:

Thus the function call RegExp(…) is equivalent to the object creation expression new RegExp(…) with the same arguments.

But empirically (in at least JavaScriptCore, SpiderMonkey, and V8), these calls are not equivalent:

> r = /a/;
/a/
> RegExp(r) === r
true
> new RegExp(r) === r
false

and looking at the steps in §22.2.4.1, it should only be possible for the RegExp constructor to return its argument unchanged (2.b.ii) when NewTarget is undefined, i.e. it was called as RegExp(…) rather than new RegExp(…).

Does the equivalence claim need to be corrected? It seems to have motivated an incorrect optimization in the SWC minifier.

1 Like

Yep, agreed this looks incorrect. Could you raise an issue? Issues · tc39/ecma262 · GitHub

Issue for reference: Claimed equivalence between `RegExp(…)` and `new RegExp(…)` doesn’t hold · Issue #3028 · tc39/ecma262 · GitHub

1 Like