lazydev
lazydev

Reputation: 432

Why does String.prototype.match() return null instead of empty array?

Example taken from MDN webdocs

var paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
var regex = /[A-Z]/g;
var found = paragraph.match(regex);

console.log(found); // will return an array of matches and returns null when nothing matches.

I would like to know the reasoning behind returning null instead of returning an Empty Array when nothing matches.

Upvotes: 5

Views: 1623

Answers (1)

zerkms
zerkms

Reputation: 254916

That's how String.prototype.match is defined in the EcmaScript standard

  1. 21.1.3.11String.prototype.match ( regexp )
  2. 21.2.5.7RegExp.prototype [ @@match ] ( string )
  3. 21.2.5.2.2Runtime Semantics: RegExpBuiltinExec ( R, S )

In short: if nothing matches - it returns null by the standard.

Upvotes: 2

Related Questions