The second "for" loop for searching your name in text


can someone explain how the second "for" loop inside the first "for" loop part of the "search you name in text" works? for e.g why do they start using for(var j=i... instead of I=(numerical value) Can someone also explain, how the "push"ing of the array works.

here is the code:(it is not mine)

var text="qeytpoqewarturwqpeoituweartur"


var hits=[];

for(var i=0; i

// The if statement will say: if you see something interesting, push that text into an array!"
if (text[i]==='a'){
    for(var j=i; j<i + myName.length; j++){



By using the mechanism you know where to continue reading in your 1st loop
after exiting the 2nd loop

         i                       <<1st Loop
         j   |                   <<2nd Loop
    i + myName.length


google search
== the Book ==
javascript [your question]
javascript push array
(also look in left-hand collumn Methods.... )

== discussions / opinions ==
javascript [your question]
javascript push array

== guidance == <---JavaScript code-convention

Your second for loop stuck

I was very confused about this,
i + myName.length

Are you saying that the i iterator (of 1st for loop) loops through the text, stopping at the first letter of the myName; and then the j iterator (of 2nd for loop) picks up the position of the 1st loop and pushes through to the end of myName.length? And that is why we + i to this code?

If so, your diagram is the best way to describe this.


Could you also explain something about this bit of code?
Why does the code run only when, i < text.length and j < (myName.length + i)?
why do i and j have to be less than what follows them?

for (var i = 0; i < text.length; i++) {
if (text[i] === "J") {
for (var j = i; j < (myName.length + i); j++) {



If you define a string
Javascript will automatically give you

  • the length property
  • and you have access to several String.prototype Methods ( see left-hand column )

Javascript starts counting at zero
thus the 1st letter would be at javascript-position 0

"This String" has 11 characters
a "This String".length will return 11
but to get at the 1st Character you would use "This String"[0] ===>> T
but a "This String"[11] would return an undefined


I see. So this issue has to do with the difference between the index count for "This String" as 0 to 10; whereas the actual count is 11? We need to specify in the for loop, therefore, that i < string.length because i count is 0 to 10 while string.length count is 1 to 11.

Thanks so much