-1

Hi I am currently doing a javascript course at Code Academy pertaining to "for" loops.

but this exercise does not make sense to me and it is pointless going further without understanding why I am doing what i am doing... here with the code.

text = "Blah blah blah blah blah blah Eric \
blah blah blah Eric blah blah Eric blah blah \
blah blah blah blah blah Eric";

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

// Look for "E" in the text
for(var i = 0; i < text.length; i++) {
  if (text[i] === "E") {
      // If we find it, add characters up to
      // the length of my name to the array
    for(var j = i; j < (myName.length + i); j++) {
        hits.push(text[j]);
    }
  }
}

if (hits.length === 0) {
  console.log("Your name wasn't found!");
} else {
  console.log(hits);
}

I get the first loop but what confuses me is the whole second loop inside the if statement....

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

just dont understand what i am doing?

9
  • 1
    The code doesn't make sense because it doesn't check that the 2nd letter is an "r", the 3rd is an "i", etc. (It simply pushes the letters at index text[i..i+myName.length-1] onto the hits array.) The conditional if-statement should likely be inside the inner loop, with a slight modification also taking myName[..] into account. The hits array should only be added to when a "complete" name is found. Commented Aug 15, 2014 at 11:46
  • What is the exercise? Who has written that code, is it the suggested solution? Commented Aug 15, 2014 at 11:47
  • this is the javascript beginners course at codeacademy.com. it does validate and works..... but i just dont understand whats going on Commented Aug 15, 2014 at 11:50
  • @GavinWood It most certainly does not work. (Note that it incorrectly "finds" my name, Paul.) Commented Aug 15, 2014 at 11:52
  • 1
    @GavinWood It doesn't count the characters within the name either. It is rubbish as it is written - no wonder why it is confusing. Commented Aug 15, 2014 at 11:54

3 Answers 3

1

The second loop is looping is basically adding the rest of the letters for your name into the array

j = i --> This means that it will start at the position of i, which is where it found an "E" in your case

j < (myname.length + i) --> is taking the length of your name + i which will give you the position up until the end of your name

j++ --> this is incrememting j by 1

hits.push(text[j]) --> This will push the next letter to the hits array based on the j index

So basically, the inner loop starts at the first letter of your name, then runs the length of your name, adding the rest of the letters from the string to the hits array, which ends up adding your the letters of your name into the array

You will end up with the array looking as such hits = {E,r,i,c,E,r,i,c,E,r,i,c}

Sign up to request clarification or add additional context in comments.

5 Comments

Except the inner loop has nothing to do with "your name" except for using the length. Consider: text = "Blah blah Enchilada Eating Elephant Emits Electric Eels Everyday blah blah".
Well, my explanantion is still correct based on the scope of the exercise that is written on code academy. I understand that there would need to be proper validation, but it is one of the first few JS exercises, they are starting from the basics
I still think that it is misleading to continue on with sentences like "which ends up adding your the letters of your name into the array". This may be the result with the particular input original presented, but the code is so far broken that .. meh.
Thank @LemuelBotha why myname.length + i then i ++... sorry i know I might sound stupid but im trying to grasp this
@GavinWood -- its not i++, its j++ Basically, what is happening is that it wants to get the characters of the myname variable into the array, so its saying myname.length = 4 + the index of i, if you count this out, it is 34, so it will stop looping once j = 34, for the first iteration, if you did not have the + i, it would stop loopong at 4
1

It starts a new loop from the index where the character E was found in the initial text up until the myName.length + i index, which bascially loop over the substring described by myName. For each iteration of that loop, it's adding the currently iterated over character to hits.

Please note that the code infers that everything starting with E is equal to yourName, which is quite naive.

Why myName.length + i?

  1. Imagine you have this text: aaaaEric.
  2. Then you loop until E, so i = 4.
  3. Now you want to loop over Eric in the subloop.
  4. If you do not add i to the condition, you end up with j = 4; j < 4; j++, which will not loop at all. You must add where you at (i) to the end condition which will give j = 4; j < 8; j++ and correctly loop over Eric, then return to the main loop.

At the end hits should look like ['E','r','i','c','E','r','i','c','E','r','i','c'] in this case.

Comments

0

The "exercise" is a steaming load of post-refined matter. Here is a "fixed exercise" that should hopefully make more sense, complete with an inline explanation. (And if this is understood, the "example" nonsense should at least be a bit more clear.)

var text = "Blah blah ELEPHANT blah blah blah Eric \
            blah blah blah Eric blah blah Eric blah blah \
            blah blah blah EGRET blah Eric";

var name = "Eric";
var foundAt = [];

// Loop through the text one character at a time over the
// indices [0, text.length), incrementing i by at the end of each loop.
for(var i = 0; i < text.length; i++) {
  // And for every index in the text, start to loop over the indices in
  // our name, or from [0, name.length). Once again, the increment to
  // j happens at the end of each loop.
  for (var j = 0; j < name.length; j++) {
      // Look at where we currently are in the text, and compare the
      // character where we are currently looking in our name.
      // (Note that we look at character i+j into the text, because we
      // look 0+j into the name.)
      if (text[i + j] == name[j]) {
         // Yup, still matches our name!
         if (j == name.length - 1) {
            // The last character matched too. This must be our name, or
            // our name was found as part of a longer word.
            // Let's record the index in the text where our name started!
            foundAt.push(i);
         }
      } else {
         // Did not match our name, so we stop looking through the rest
         // of the name and continue looking through the next character
         // in the text (this terminates the inner loop early).
         break;
      }
  }
}

if (foundAt.length) {
    // \o/ Hooray!! \o/
    // We found our name at least once, show where it was found.
    console.log(foundAt);
} else {
    console.log("Nope, nothing here");
}

And a fiddle. Try changing the name.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.