Trying to understanding how the output of a loop is achieved

Hello, this is my first time on the forums so I’ll try and be as precise to my problem as I can! :slight_smile:

( I can’t seem to get a direct URL to the quiz question, but I can link to the review that appears just before the quiz : https://www.codecademy.com/practice/paths/web-development/tracks/web-dev-js-arrays-loops-objects/modules/learn-javascript-loops )

The question ask: “Which of the following for loop definitions will result in the word 'loop' being extracted from the phrase 'proof of lag' ?”

The code to the question is a fill in the blank:

const phrase = 'proof of lag';

result = '';
for (let i = ____ ; i ____ ; i ____ ) {
  result += phrase[i];
}
console.log(result);

With the answer choices being:

for (let i = phrase.length - 3; i > 0; i -= 2)
for (let i = phrase.length - 2; i >= 0; i -= 3)
for (let i = phrase.length - 3; i >= 0; i -= 3)
for (let i = phrase.length - 3; i > 0; i -= 3)

I thought I understood loops well enough, but this has just completely confused me! It’s supposed to output the word ‘loop’ by iterating through the string, by choosing the letters by index which would output the word. That much I know. My problem is, I can’t tell how any of the solutions provided would achieve that.

When I choose the second solution, it tells me that it would output ‘affr’. How are these solutions skipping over indices in the string/array?

It wants us to construct the word loop by extracting letters from the phrase.

We want to start three letters from the end, end on the first letter, and step backwards by threes.

Yes. It wants ‘loop’ to be extracted from the string, put into empty string of result, and returned to the console. It’s difficult to get a screenshot. (Can’t seem to land on the quiz containing the question).

My logic was that the iterator was initialized to two indices subtracted from the end of the string, so that it started on the ‘l’ of the word ‘lag’. But would the increments count from 1, starting at ‘g’? (Talking about solution 2) I didn’t really know what to make of the increments at the end.

So l is actually 3 less than the length, the letters we want are every third one going right to left from there, so a step of -3, and we want to include the first letter, so i >= 0.

1 Like

From looking at your explanation. I also realized that the spaces counted as indices as well! Eureka haha! This has helped me a lot. And I can actually go apply this to a project I was stuck on, right away! Thank you very much!

1 Like