Learning Loops Quiz Question/Nested Loops - Can Someone Explain?

Hi everyone! I’m new to JavaScript & loops and I’m trying to understand the output for this nested loop example (link to quiz below).

Example:

const animal = ‘cat’;

for (let i = 0; i < animal.length; i++) {
console.log(animal[i]);
for (let j = 1; j < 4; j++) {
console.log(j);

Why is the output c123a123t123 rather than cat123?

I’m confused as to why the string in index 0 is being broken up in between the output of j, if someone would be able to help me understand I’d really appreciate it!

https://www.codecademy.com/paths/full-stack-engineer-career-path/tracks/fscp-javascript-syntax-part-ii/modules/fecp-learn-javascript-syntax-loops/quizzes/loops-quiz

Hello, and welcome to the forums!

const animal = "cat";

for (let i = 0; i < animal.length; i++) {
  console.log(animal[i]);
  for (let j = 1; j < 4; j++) {
    console.log(j);
  }
}

Since the 2nd for loop is nested inside of the 1st for loop’s code block, the 2nd one will run a full cycle each time the 1st one loops.

So for each letter of the animal string, the for loop that counts from 1 to 3 is run. It doesn’t move to the next letter until the nested loop completes too.

3 Likes

Welcome to the forums, @adriennemt7!

Also, to add to what @selectall has said above. If you’re trying to print cat123 instead of c123a123t123, why don’t you try removing the second for loop from the nest of the first for loop. This way, you’d get cat printed first, followed by 123.

So, instead of doing:

for(iteration syntax) {
    statements
    for(iteration syntax) {
          statements
    }
}

Try doing:

for(iteration syntax) {
    statements
}
for(iteration syntax) {
    statements
}

This should help you print the correct form. :slight_smile:

1 Like

Thank you for your help!

Thank you very much for your help! :smile: