I can't figure out why this is the answer in loops quiz

The code is:

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);
  }
}

And the answer is:

c 1 2 3 a 1 2 3 t 1 2 3

I thought the answer was the following and can’t figure out why it isn’t:

`

1 cat 2 cat 3 cat

`

The actual output is:

c
1
2
3
a
1
2
3
t
1
2
3

console.log() starts a new line each time it is called.

If take a pencil, and write down the output on a sheet of paper while executing each line of code in order, you’ll see how the nested for loop is executed once for each letter in the string, 'cat'. You can use a tool like this to help with visualizing code.

Due to the loops being nested, the first loop would execute once, printing out the [i] character from Cat which is 0 = ‘C’. it then goes into the inner loop and that loop runs until it is completed, printing 1 2 3 as those are the values of j. Once the nested loop is completed, it returns back to the outer loop and (i) has incremented to 1, thus printing ‘a’ and so on.

Resulting in in what @midlindner had said.

I see now! Thank you!

1 Like