Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Why does JavaScript return different results for RegExp test() method with empty object?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading