I recently came across a code snippet (a joke) where the test()
method of JavaScript’s RegExp
object was used with an empty object as an argument. Here’s the code:
console.log(new RegExp({}).test('mom')); // true
console.log(new RegExp({}).test('dad')); // false
Can someone explain why is it happens?
2
Answers
The
RegExp
constructor casts the first argument to a string. An empty object becomesGiven this represents a regexp character class, essentially
"mom"
passes because it contains an"o"
.This is a curious fact. RegExp constructor accepts a string as its first argument. Since you are passing
{}
it gets coerced to string, and the coercion of an object is the literal string[object Object]
.By a fortuitous coincidence, the square brackets have a precise meaning in a regular expression, and it means "one of these characters of the set".
Thus, the regular expression is equal to
[objectO ]
. In other words, your code is equal to:which is equal to:
which means: tests
true
if any of these characters is present: o, b, j, e, c, t, O, space.mom
satisfies this condition, whiledad
doesn’t.