Understanding the Second Loop at Codecademy’s Search Text

What is the purpose of the second loop j?

The second loop is a subroutine used to push characters to array hits[] based on the length of the word being searched.

What happens to the first loop once the second loop kicks in?

Once the first character of the word being searched is found, the first loop waits until the second loop finishes running, which it will run for the length of the word being searched and it starts at the position of the first character searched (position i ), + the length of the word being searched.

Here’s a test showing what happens to the count of both loops. For the purposes of testing, I’ve included  a console.log inside of each loop in order to monitor the count in real time:

 var text = "Bla bla Tony bla bla";

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

for (var i = 0; i < text.length; i++) {
    console.log("i= " + i);
    if (text[i] === "T") {

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

    }
}

Result:
i= 0, i= 1 , i= 2, i= 3, i= 4, i= 5 , i= 6, i= 7, i= 8
j= 8, j= 9, j= 10, j= 11,
i= 9, i= 10, i= 11, i= 12, i= 13, i= 14, i= 15, i= 16, i= 17, i= 18, i= 19

In summary, the first loop is interrupted when the second loop starts. Once the second loop finishes pushing characters into array hits[], the first loop resumes its execution until it reaches the end of text or finds another first character matching my search criteria.

Question:

What would happen if instead of  j < (myName.length + i); we would write j < myName.length; (without + i)?

Here’s the result:

i= 0, i= 1, i= 2, i= 3, i= 4, i= 5, i= 6, i= 7, i= 8, i= 9, i= 10, i= 11, i= 12, i= 13, i= 14, i= 15, i= 16, i= 17, i= 18, i= 19

The word Tony is text‘s positions 8, 9, 10, 11.

Without myName.length + i these positions would not have been referenced because it would have been like saying:
j = 8; j  < 4;  j++

Since we start at the count of 8, the count of 4 has already been passed.
(4 being the length of Tony).  So the second loop would not work at all and that’s why we need 4 + 8 which will give us the counts of 8,9,10,11

There is a more efficient way to create this search script. You can see it on the following link
Javascript Searching For a Word in a String

Advertisements

Author: tarau

technical writer, web technologies

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s