Skip to content
Advertisement

Javascritpt – Looping through an array

So i just started learning js and i can’t solve this excercise:

Create a file named looping-through-arrays.js.

In that file, define a variable named pets that references this array:

['cat', 'dog', 'rat']

Create a for loop that changes each string in the array so that they are plural.

You will use a statement like this inside the for loop:

pets[i] = pets[i] + 's'

I tried something like this code but apparently it doesn’t work:

let pets = ["cat", "dog", "rat"];
for(let i = 0; i <= pets.length; i++){
  pets[i] = pets[i] + "s";
};
console.log(pets);

Advertisement

Answer

//Try this one   
 let pets = ["cat", "dog", "rat"];
    for(let i = 0; i < pets.length; i++){
      pets[i] = pets[i] + "s";
    };
    console.log(pets);
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement