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?
>Solution :
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:
console.log(new RegExp('[object Object]').test('mom'));
which is equal to:
console.log(new RegExp('[objectO ]').test('mom'));
which means: tests true if any of these characters is present: o, b, j, e, c, t, O, space. mom satisfies this condition, while dad doesn’t.