2

What is the difference between RegExp('hi') and new RegExp('hi')?

Does the new keyword do anything here?

Evan Hahn
  • 12,147
  • 9
  • 41
  • 59
  • Constructor should be use for situations like this: `RegExp('hi' + someVariable)` where you actually construct (duh!) an expression. If you know it from the beginning go with `/hi/`. – The Witness Aug 29 '16 at 21:52
  • `function MyObject(arg) { if (!(this instanceof MyObject)) return new MyObject(arg); }` is a common way to implement this yourself as well. – 4castle Aug 29 '16 at 22:27

1 Answers1

5

It is identical

The RegExp constructor is the %RegExp% intrinsic object and the initial value of the RegExp property of the global object. When RegExp is called as a function rather than as a constructor, it creates and initializes a new RegExp object. Thus the function call RegExp(…) is equivalent to the object creation expression new RegExp(…) with the same arguments.

From http://www.ecma-international.org/ecma-262/6.0/#sec-regexp-constructor

zerkms
  • 249,484
  • 69
  • 436
  • 539
  • I can't help but feel this should be community wiki, since there's pretty much 0 original content in this answer. – 4castle Aug 29 '16 at 22:29
  • @4castle I personally don't know the criteria for an answer to be a good community wiki post. I checked http://meta.stackexchange.com/questions/11740/what-are-community-wiki-posts and not sure that being "not much original" is one of those. – zerkms Aug 29 '16 at 22:57