Training on Exes and Ohs | Codewars


function XO(str) {
var x = str.match(/x/gi)
var o = str.match(/o/gi)
return (x && x.length) == (o && o.length)


Why is the x && x.length or o && o.length necessary? I tired just x.length && o.length and this didn’t seem to work. I know it’s in reference to the case in which they are empty arrays, but what is it about say “null && null.length” that’s missing from just “null” ?

I’m trying to visualise this by running things like “null == 5” and comparing it to “(null && null.length) == ([o, o, o, o, o] && 5)”. Why does only the latter return the expected false?

When match doesn’t find any matches it returns null. What happens if you try to do null.length? Open the console in your web brower’s dev tools and type null.length at the prompt at the bottom. That’s why you need to check if the value is not null first before you try to check its length.

1 Like

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.