dwyl / learn-javascript

A Series of Simple Steps in JavaScript :-)
Other
64 stars 15 forks source link

JSHint "Unexpected token else" #28

Closed NehemiahAT closed 6 years ago

NehemiahAT commented 6 years ago

I'm having some issues with a speed tester I'm creating in JS. So, the code I'm having trouble with is this: var num1 = 1; while (num1 <4000000000000000) {num1++; document.write("Loading...");} else if (num1 == 4000000000000000) {document.write(num1);} else {document.write("An unexpected error occurred, please try again.");}

What it's meant to do is say "Loading..." while it's repeatedly incrementing num1 until it reaches 4000000000000000. Then display "4000000000000000". JSHint keeps telling me "Unexpected token else", but I can't figure it out.

bobwhitelock commented 6 years ago

The issue is with your else if - else if is only valid syntax immediately after if (...) {...}, but you've used it after while. If I understand what you're trying to do I think you'll want to change the while to if and surround the whole section in a while or for loop where you handle the incrementing of num1. Hope this helps.

NehemiahAT commented 6 years ago

Thanks. But I don't know how I could surround that section in a while loop. The closest I can get is var num1 = 1; while (num1 <4000000000000000) {num1++; document.write("Loading...");} if (num1 == 4000000000000000) {document.write(num1);} else {document.write("An unexpected error occured, please try again.");}

But, I get an infinite amount of "Loading..."s and JSHint says "Infinite loop found on line 0. The line number is approximated so look carefully."

bobwhitelock commented 6 years ago

Your while loop only contains {num1++; document.write("Loading...");}, which is why Loading... is being printed, and 4000000000000000 is a pretty big number so this is going to happen a lot of times before anything else occurs. Once this loop has finished I would expect 4000000000000000 to be printed, but without testing it I imagine this could take hours or days. I'd suggest trying using a much smaller number, like 100, so you can better see what's going on.

NehemiahAT commented 6 years ago

Ok, thanks! I tried it on 400 and it worked.