2

Why can we pass Number, Boolean or String to an Array map but not RegExp? Could be something noob, but just trying to get my head around on the basic difference between these constructors?

let array = ["10", "20", "30", "40", "0"];

console.log("Boolean",array.map(Boolean));

console.log("Number",array.map(Number));

console.log("RegExp",array.map(x=>new RegExp(x)));
//cannot do array.map(RegExp)
sabithpocker
  • 15,274
  • 1
  • 42
  • 75

1 Answers1

3

When you call:

array.map(RegExp);

You get:

Uncaught SyntaxError: Invalid flags supplied to RegExp constructor '0'

The function you pass to map gets called with more than one argument (currentValue, index, array).

RegExp (unlike Boolean and Number) makes use of the second argument (it describes the flags that should be applied to the regex, such as "g" for global). A number (which the index is) is not a valid flag name.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Can we conclude that the only way of mapping an array to `RegExp` is `x=>new RegExp(x))`. Or can there be any other hacky options by just binding second param? Just curious! – sabithpocker Oct 14 '16 at 10:51
  • @sabithpocker Yes, you could write a function `function firstArg(fn) { return function(a) { return fn(a); }; }`, then do `array.map(firstArg(RegExp))`. –  Oct 14 '16 at 10:57