hits1 is an array, its length is equal to the number of elements put into it. hits1.push(i) puts a number i in it if a match is found in text with the string myName. The if (hits1.length) decrypted as if ((bool)hits1.length) , while (bool) returns false if it has been given a void or 0, and true in other cases. Accordingly, if this length turns out to be zero (i.e. no match is found), the list of matches does not attempt to be output; if not zero, the array is looped.

And why it does not work when you write if(hits.length === 0)

  • 3
    Everything works. - Konstantin Pl

1 answer 1

In general, in your case everything works. However, I can assume the following. If you write something like:

 var fff = 0; if(fff.length === 0) { console.log("ok"); } else { console.log(fff.length); } 

That output will be udefined . This is due to the fact that fff not an array; the call fff.length returns undefined , not 0. If you write var fff = []; then everything will work correctly. It is also worth knowing that identity verification === does not convert types at all. The truth here will be if only on the right and on the left there will be identical values ​​(for example, undefined === undefined ). For type conversion, use == equality (for example, '' == 0 or undefined == null )