skip to Main Content

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


  1. The RegExp constructor casts the first argument to a string. An empty object becomes

    new RegExp('[object Object]')
    

    Given this represents a regexp character class, essentially

    /[objectO ]/
    

    "mom" passes because it contains an "o".

    Login or Signup to reply.
  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search