1

I'm just learning JavaScript and I'm trying to have an if else statement declare something, but I want to use a loop with it. Basically something like this:

var myNum = 1;
var linebreak = "<br />";
var d3d = "You're very lucky! ^_^";
var p3p = "<p>Too Bad. Maybe Next Time.</p>";
for (myNum = 0; myNum < 7; myNum++) {
    if (myNum == 7) {
        document.write(myNum + linebreak + d3d + myNum);
    } else {
        document.write(p3p + "You're not very lucky today...");
    };
}

It would say You're not very lucky for the first 6 loops, but at the 7th loop it would say you're very lucky. I know something is wrong, because if it was written correctly, then at the end of the loop it would write the if statement. I know you'd usually have the for loop variable set as "i", but I also need the if else statement to be able to know what that is. Does anyone know what I'm doing wrong?

1 Answer 1

1

Your loop never actually reaches 7 because your condition is to continue if myNum is below 7. To keep it at seven iterations and do what you want, you'd have to check to see if (myNum == 6). On a side note, to understand loops better, you can try running this code:

for(var i = 0; i < 5; i++)
    alert(i);

for(var i = 0; i <= 5; i++)
    alert(i);
Sign up to request clarification or add additional context in comments.

4 Comments

I figured it out the second you answered, but yes. It's because it doesn't reach 7. I needed to have myNum <= 7, instead of myNum < 7.
If this answer helped you, don't forget to consider choosing it as the solution to your question by clicking the green checkmark to the left. meta.stackexchange.com/questions/5234/…
I was actually waiting for the 8 minute timer to finish lol, but I clicked it. Thanks.
No problem, just making sure new users know how the site works :)

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.