Need help, Need someone to explain this example from loops article

I need someone to explain this code below, as I have learned about template literal, I thought that the result would be something like this:
my cats are called Pete, my cats are called Biggles, my cats are called Jasmine,
Need help to explain the result from the code below!

const cats = ['Pete', 'Biggles', 'Jasmine'];

let myFavoriteCats = 'My cats are called ';

for (const cat of cats) {
  myFavoriteCats = `${myFavoriteCats}${cat}, `
}

console.log(myFavoriteCats); // "My cats are called Pete, Biggles, Jasmine, "

Hi @AnsBdran

Maybe it’s easier to understand when you put the console.log() inside the loop. Then you see the changes after every round.

const cats = ['Pete', 'Biggles', 'Jasmine'];

let myFavoriteCats = 'My cats are called ';

for (const cat of cats) {
  myFavoriteCats = `${myFavoriteCats}${cat}, `
  console.log(myFavoriteCats);
}

// "My cats are called Pete, "
// "My cats are called Pete, Biggles, "
// "My cats are called Pete, Biggles, Jasmine, "

You are adding a cat name to the original string myFavoriteCats every round. At the start of the second round myFavoriteCats has "Pete, " attached from the first round and now "Biggles, " gets added (and so on).

By the way: If we want to extend a string like in this example it is easier to use the += operator. That’s the short version of adding something and saving it in the same variable. The below code is equivalent to the line inside your loop:

myFavoriteCats += `${cat}, `;

Does that help? Feel free to ask if something isn’t clear, yet. :slightly_smiling_face:

Have a nice day,
Michael

1 Like

Thanks Michael
that was a perfect explanation, I get it now.
thank you.

1 Like