If you want to "run a loop" ... you'll need to run a loop! : )
for (var i = 0; i < 10; i++) {
// do things!
}
These loops are ugly and scary!
But - it's really just a start {
and an end }
to some instructions.
Then there a few other things.
for (some setup
, a condition
, what to do after each loop
)
- setup: make a variable to keep track of each time it runs through the directions (This is usually written
i
but it's just a convention - and it's for "iterator" or "index" or whatever. It can be anything you want. The setup can also be more complex
- condition: as long as this
i
thing is lower than 10, run the loop again
- after each loop: increment the
i
by one
So - the loop should just run whatever code is inside it... 10? times? or 11?
for (var counter = 0; counter < 10; counter++) {
console.log('curerntly...', counter);
}
Now... what goes inside?
That's where the %
bit comes in. This is the classic "fizz buzz" type of test.
for (var i = 0; i < 10; i++) {
var message = 'Marco';
var isOdd = (i % 2) != 0; // if it can't be evenly divided by 2...
if (isOdd) {
message = 'Polo';
}
console.log(message);
}
https://jsfiddle.net/sheriffderek/dtkj0aby/
and you can write it in many different ways too.
for (var i = 0; i < 10; i++) {
console.log( (i % 2) != 0 ? "Marco" : "Polo" );
}
but that's pretty ugly! (yes, you can even make it shorter...)
So, stick to what is helping you and your team read it instead of trying to get too crazy and unreadable!!! The code is just as much for the humans as it is for the computer. It's our shared language.