Check to see if a string has the same amount of 'x's and 'o's. The method must return a boolean and be case insensitive. The string can contain any char.
Someone posted their answer is like this but I don't understand the part x && x.length. Can someone explain this?
function XO(str) {
let x = str.match(/x/gi);
let o = str.match(/o/gi);
return (x && x.length) === (o && o.length);
}
str.match(/x/gi) returns an array of matches if there are any matches. But if there aren't any matches, it returns null. You can't get the length of null, so x && x.length makes use of short-circuiting to prevent that error. It will be null if x === null, otherwise it will be the lenth of the array.
The same goes for o && o.length. So if both return matches, it compares the number of matches. If both have zero matches, it turns into null === null, which is true. And if only one of them has matches, null will not be equal to the length of the matches.