Doubt about looping

Hello folks!

I have a silly doubt about looping.

for (let i = 0; i < cats.length; i++) {
  if (i === cats.length - 1) {
    info += 'and ' + cats[i] + '.'; //why this line select the final index of the array???
  } else {
    info += cats[i] + ', '; // why this one select all the array???
  }
}

Does anyone knows why one argument select just the final word of the array and the second select the whole array??for me both lines looks quite the same! It doesn’t make any sense to me :frowning:

Thank you all! :slight_smile:

Hi @rodrigoguima!

This is to do with the bit inside the if () parentheses — if (i === cats.length - 1) is saying “if the value of i is equal to the last item in the array, run the code inside the curly braces.”

If this statement is not true, the line of code in the curly braces after the else keyword runs instead.

So the first line runs only for the final array item, and the second line runs for all the others.

The reason that cats.length - 1 is equal to the last item in the array is because computers count from zero. if array.length is equal to 7, for example (7 items in the array), then the last item will be in index position 6 — the index positions are 0, 1, 2, 3, 4 , 5 , and 6. So to get the last item you need array.length - 1, not array.length

1 Like

@chrisdavidmills Thank you very much! now I got it! :slight_smile:

hey Chris! just another thing!
why in this case when I remove “info” from this loop it show me only the the last item of the array?

let info = 'My cats are called ';
const para = document.querySelector('p');

for (let i = 0; i < cats.length; i++) {
  info += cats[i] + ', '; //in this case I receive all cats names.
}

para.textContent = info; ```

in other hand...

``` const cats = ['Bill', 'Jeff', 'Pete', 'Biggles', 'Jasmin'];
let info = 'My cats are called ';
const para = document.querySelector('p');

for (let i = 0; i < cats.length; i++) {
  cats[i] + ', '; //in this case I receive only the last cat name "Jasmin".
}

para.textContent = info; ```

also, is possible to print all cats names?

I’ve tried it, and it doesn’t print any of the cats names :wink:

This is what I’d expect, to be honest - if you remove info += , then you are not doing anything with the cat names - you are not assigning them to anything or adding them anywhere.

also, is possible to print all cats names?

Isn’t this what the original demo is doing anyway? I don’t understand how this is different.

hey @chrisdavidmills! I got here a screenshot of my terminal!

This is the original exemple:

this is what it prints when I remove info:

Isn’t this what the original demo is doing anyway? I don’t understand how this is different.

I mean, in the first example with info += cats[i] + ', '; the cats array is entire printed, but when I remove info infoonly the last cat name is printed... I mean wasn't that supposed to print the entire array as well? (withoutinfo`).

Thank you!! :slight_smile: