6.Log IT -Help understanding why hits equal to zero


#1


https://www.codecademy.com/courses/javascript-beginner-en-XEDZA/0/6?curriculum_id=506324b3a7dffd00020bf661#


Code doesn't behave incorrectly, however, i am trying to understand the second portion of this code:
hits.length would give me each letter of myName found in the text. 'A','K','S',....etc. In total 18 letters. In the hint section, it showed to use hits.length equaling a zero numerical value. Why are we doing this? hits.length will never equal zero. So the second argument under else { will always be true, wouldn't it?. please help understand the WHY here. Thanks.


if(hits.length===0){
    console.log("Your name wasn't found!");
} else {
    console.log(hits);
}


#2
var hits = []
console.log(hits.length);    // 0

It will remain zero until something is pushed on to the array.


#3

Thanks for reply. So i guess the code before that:-

for (var i=0;i<=text.length;i++){
if (text[i]===myName[0]){
for (var j = i;j<(i+myName.length);j++){
hits.push(text[j]);}

^So i guess the code hits.push "pushes" the values in the hits[] array. which if your letter was found atleast once in the text variable it would equal 1 or greater, hence, the if(hits.length===0){ <- to equate to FALSE argument and instead the console will show us the second TRUE argument and give us console.log(hits);. Okay that makes sense. Thank you for reply.


#4

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