Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

How can I put this loop within this function?

Hello,

Here is a function that I have, and I want to have it loop through my array of objects until it reaches the 7th loop, and then it prints out a different message to the document.

Why wouldn't this work?

function printChores() {

for (let i = 0; i < 7; i += 1;) {
var name = chores[Math.floor(Math.random() * chores.length)];
document.write ('<p>' + 'Who: ' + name.Who + '' + '</p>');
var task = chores[Math.floor(Math.random() * chores.length)];
document.write ('<p>' + 'Chore: ' + task.What + '' + '</p>');
} else
{ 
document.write ("yay!");
}
}

// This calls the function
printChores()

2 Answers

You cannot have an else clause attached to a for loop. It's connected to an if / else if chain.

In your case, you would want to complete the loop 7 times, and then, when you're out of the loop (what we call scope), add the next part of your code; in this case, the new document.write() statement.

for (let i = 0; i < 7; i += 1;) {
  var name = chores[Math.floor(Math.random() * chores.length)];
  document.write ('<p>' + 'Who: ' + name.Who + '' + '</p>');
  var task = chores[Math.floor(Math.random() * chores.length)];
  document.write ('<p>' + 'Chore: ' + task.What + '' + '</p>');
} 
document.write ("yay!");

// This calls the function
printChores()

Okay, yeah I see.

I ran everything without the else in there and it printed to the document 7 times. That’s not exactly what I’m looking for....I understand why it did it but I’m having trouble getting what I want.

I want it to print to the document once and on the seventh time print the other message.

How could I get that?

So what you really want is the 7th task? If that's the case then you don't need a loop; you can access the 7th element directly by using chores[6].

If not, I'm not entirely sure what you're trying to do. You only need a for loop if you want to iterate over every value of the array. If you're only trying to print 2 messages, you do not need a for loop to accomplish that unless you're trying to find a specific value in an unsorted collection.