0

Say I have the following code:

const isArrayField = type => !!type.match(/^Array\[\w+\]$/);

const type = 'Array[IncidentRole]';

console.log(isArrayField(type));

All I need to know is if the string matched the regex. I don’t need the matches. In this case, is it safe to use !! to force isArrayField to return a boolean? If not, why?

Brandon Durham
  • 7,096
  • 13
  • 64
  • 101

1 Answers1

3

It's safe, yes. If it matches, match will return an array, and !anyArray is false, so !!anyArray is true. If it doesn't match, match returns null, and !null is true so !!null is false. There aren't any lurking TypeErrors waiting to happen or similar. :-)

But there's a better answer: The test function on the regex, which returns a boolean:

const isArrayField = type => /^Array\[\w+\]$/.test(type);
// −−−−−−−−−−−−−−−−−−−−−−−−−−^^^^^^^^^^^^^^^^^^^^^^^^^^^

const type = 'Array[IncidentRole]';

console.log(isArrayField(type));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875