0

I am a javascript newbie. I have to create a var pets with an array ['cat', 'dog', 'rat'] and by using for loop I have make each strings in that array plural.

My code is:

var pets = ['cat', 'dog', 'rat'];
for (pets[i] = pets[i] + 's';) {    

};
console.log(pets);

Error is:

for (pets[i] = pets[i] + 's';) {    
                         ^
Could not run: Unexpected token ) 
2
  • Start with proper for-loop syntax Commented Jan 4, 2016 at 10:11
  • 1
    for (pets[i] = pets[i] + 's';) huh? see MDN for doc Commented Jan 4, 2016 at 10:12

2 Answers 2

4

The syntax of the for loop is incorrect. It'll throw Syntax Errors.

The Correct syntax is:

for ([initialization]; [condition]; [final-expression])
    statement

Updated Code:

for(var i = 0; i < pets.length; i++) {
    pets[i] = pets[i] + 's';
}

You can even write this in single line, taking advantage of the last expression of the for which is evaluated after each iteration.

for(var i = 0; i < pets.length; pets[i] = pets[i] + 's', i++);

Note: Multiple expression are separated by using ,-comma operator.

Sign up to request clarification or add additional context in comments.

1 Comment

for(var i = 0; i < pets.length; pets[i] = pets[i] + 's',i++); shortened little bit.
3

Your for loop is messed up, it can surely be done using for-loop but I would suggest you to use Array.prototype.map()

var pets = ['cat', 'dog', 'rat'];
pets = pets.map(function(el){
   return el+"s";
});

The map() method creates a new array with the results of calling a provided function on every element in this array.

In ECMAScript2015 arrow function

var pets = ['cat', 'dog', 'rat'];
pets = pets.map( el => el+"s");

If you still feel like using for loop and want to write some unnecessary code then do:

for(var i = 0; i < pets.length; i++){
  pets[i] = pets[i] + 's';
}

4 Comments

hey buddy i have to use for loop to iterate through arrays
Or, using fat arrow syntax: pets.map(el => el + 's');
This solution is better, but not for a newbie who cannot even properly write a loop :)
@Sagar: why do you "have to use for loop"? This answer does precisely what you asked for; if there are artificial and pointless restrictions add those to the question, don't expect us to guess your requirements.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.