I can't figure this out. I want loopCheck to count by 5s all the way to 500. I know there's an easier way than writing all those numbers out.
for (i = 1; i <= 500; i++){
var loopCheck = i === 5 || i === 10 || i === 15 || i === 20 || i === 25;
if (loopCheck === true){
alert("if statement works!!!"):
}
}
I can't figure this out. I want loopCheck to count by 5s all the way to 500. I know there's an easier way than writing all those numbers out.
for (i = 1; i <= 500; i++){
var loopCheck = i === 5 || i === 10 || i === 15 || i === 20 || i === 25;
if (loopCheck === true){
alert("if statement works!!!"):
}
}
Share
Improve this question
edited Jan 18, 2015 at 19:42
Oleg
9,3692 gold badges45 silver badges59 bronze badges
asked Jan 18, 2015 at 19:38
MattMatt
1731 silver badge14 bronze badges
3 Answers
Reset to default 9For the sake of being different:
You can use the modulo %
operator:
for (i = 1; i <= 500; i++) {
if (i % 5 === 0) { // if `i` is *perfectly* divisible by 5
// do something here
}
}
Just add 5 to i
on each iteration:
for (i = 5; i <= 500; i += 5) {
// ...
}
i += 5
is shorthand for i = i + 5
. Note that we start with i
set to 5 here.
I agree with the simplicity Bens answer, as an alternative, you can use modulo:
for (var i = 1; i <= 500; i++){
if (i%5 === 0) {
console.log(i);
}
}
That maintains the "looping through every number" but with modulo you ask "when I divide the number by 5, what remainder do I have?" If its divisible by 5, you have a remainder of 0. :)