7. result


#1

Something similar happens to me. It prints only [ ]

Can someone help me understand what is wrong with my code?

/*jshint multistr:true */
text= "ahahhahaha Alessio hahahaha annanana Alessio";
var myName="Alessio";
var hits=[];
for (i=0; i<= text.length; i++){
if (text[i] === "A"){
    for(var j=i; j<(i+ myName.length); j++){
    hits.push(text[j]);}
}
}
if(hits.length= 0){
    console.log("Your name wasn't found!");
}
else
{
    console.log(hits);
}

4/ 7 your "if" statement
#2

using a compare operator (==) instead of assigning (=) inside your if statement is highly recommended it. Otherwise, you set the length of hits to 0.


#3

Hi I was having the same problem and your solution fixed it! Could I ask you why it works only when I use === or == but fails to when i use a single =. You said that using a single = would set the length of hits to 0 but won't using === also be the same? Thank you! :slight_smile:


#4

no, those are very different. a single equal sign is used for assigning a value to a variable:

var myName="Alessio";
var hits=[];

see? Single equal sign. Where was two equal signs are used for comparison:

if (text[i] == "A"){ // do something }

3 equal signs is also comparison, but then the data type (string, integer, boolean) must also be a match:

2 == "2" // true
2 === "2" // false, 2 is a integer, "2" is a string

#5

Oh! I see it much better now, Thanks! Much appreciated!