What does if (hits1.length) ? That is, what is this length?

 var text = "Walla walla Wee Gillis salt and pepper Wee Gillis peas and carrots Wee Gillis walla walla Wee Gillis salt and pepper Wee Gillis peas and carrots"; var myName = "Wee Gillis"; var hits1 = []; for (var i = 0; i < text.length; i++) { if (text[i] === myName[0]) { if (text.substring(i, i + myName.length) === myName) { hits1.push(i); } console.log("\nsubstring\n"); if (hits1.length) { for (i = 0; i < hits1.length; i++) { console.log(hits1[i], text.substring(hits1[i], hits1[i] + myName.length)); } } } } 

    2 answers 2

    In JavaScript, the following values ​​are converted to false in if :

    • false
    • null
    • undefined
    • +0 and -0
    • NaN
    • ""

    All other values ​​are converted to true . (See specification, clause 9.2 )

    In this case, if hits1.length is 0 , then the code inside the if block if not executed.

      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.

      PS: check the balancing of {} brackets in the code, they are a little missing here.