I just can't figure out whats wrong with my code


Would be very grateful if someone could tell me whats wrong with my code, thanks :smile:

/*jshint multistr:true */

var text = "dave kdfkdf dave kdfkdfffff dave";
var myName = "dave";
var hits = new Array();

var counter;
var nameCounter;

for (counter = 0; counter <= text.length; counter++){
    if (text[counter] === myName[0]) {
        for (nameCounter = counter; nameCounter < (nameCounter + myName.length); nameCounter++) {


Okay, i switched

nameCounter < (nameCounter + myName.length);


nameCounter < (counter + myName.length);

now it works, but could you explain why?

thanks :blush:


In your code you made another variable called counter


is this answer related to my first post?


nameCounter < (counter + myName.length); --> this one works

nameCounter < (nameCounter + myName.length); --> this one does not



What is counter equal to?
What is nameCounter equal to?


I don't think I did that lesson yet (I am doing JavaScript too).


Just take a look at my first post


That is all I see, so I don't see that they equal to any thing.


there I initialize counter with 0


Maybe because you put nameCounter equal to counter


why does this cause problems here: nameCounter < (nameCounter + myName.length);? shouldn't nameCounter be equal to counter (0)?


is nameCounter=counter; valid? I don't know. By the way, why would you want to do that?


yeah it is. as long as nameCounter is smaller then nameCounter plus the length of the name I'm searching for, the for does push the strings from text into hits


I just figured it out. nameCounter < (nameCounter + myName.length) will always return true.


Great! I see that you figured it out.