Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

JS explanation please...

Trying to get an explanation on the following code:

var text = "Hey, what's happening \
my name is Paul. Your name is not Paul, is it? \
That would be super cool if it was. But alas, it's not Paul";

var myName = "Paul";

var hits = [];

for (var i = 0; i < text.length; i+=1){

    if (text[i] === 'P'){

        for ( var j = i; j < myName.length + i; j+=1 ){

            hits.push(text[j]);

            }
    }   
}

This program is supposed to cycle through the 'text' variable. When it finds the first letter of 'myName', the second for loop starts and pushes each letter of 'myName' to the empty 'hits' array.

I'm confused why there has to be

j < myName.length + i;

Instead of just

j < myName.length;

Why do we have to add ' i ' to myName.length to get the letters of 'myName' pushed to the 'hits' array?

3 Answers

Let's say the letter "P" was found at index 18. So i = 18. When you do

for ( var j = i; j < myName.length + i; j++)

you set "j" to be equal 'i" so at this point "j" is 18 as well. Next you check: if 18 is less then my name (4) plus 18, push letters. If you didn't add "i" to the condition "j" would be 18 and your name length would be 4. So "j" would be higher and the loop would not push any numbers to the array. When you add 18th to length of your name it makes 24. 18 < 24 so we push 4 letters until we get to 24 and end the loop.

I'm not good at explaining but hope that helps :)

If you didn't understand just draw the string on a paper and try to act as the program !

Makes perfect sense! Thanks!