Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is (new RegExp("\\w") === /\w/) false in JS?

I tried the following in Chrome’s console:

var r1 = new RegExp("\\w"); // → /\w/
var r2 = /\w/; // → /\w/
r1 === r2; // → false
r1 == r2; // → false
r1.toString() === r2.toString(); // → true
r1.source === r2.source; // → true

I don't understand why it does that.

like image 679
bfontaine Avatar asked Aug 25 '12 19:08

bfontaine


2 Answers

They are two different RegExp instances, so by directly comparing them with == or === you're comparing two unequal references, resulting in false.

But when you compare either their toString() serializations or their sources, you're comparing their string representations by value. Since they're basically the exact same pattern and flags, comparing their string representations will return true.

like image 185
BoltClock Avatar answered Oct 06 '22 01:10

BoltClock


Here is a quote from the Comparison Operators documentation on MDN:

Note that an object is converted into a primitive if, and only if, its comparand is a primitive. If both operands are objects, they're compared as objects, and the equality test is true only if both refer the same object.

new RegExp("\\w") is an object and so is /\w/. Both instantiated separately. Need I say more?

like image 23
Salman A Avatar answered Oct 06 '22 01:10

Salman A