Question

I have this quick code snippet:

var sQuantity = 0
if (sQuantity = 0 || isNaN(sQuantity)) {
  (sQuantity = parseInt(prompt("Let's begin compiling our student database. How many students would you like to enter?", "Number of Students")));
  (sQuantity = 1);
}

But when I run it like this, the prompt doesn't come up at all. Obviously I'm mistaken how this should work. How do I get a prompt to keep popping up if an Integer is not entered? I'm probably going about this all wrong...

Was it helpful?

Solution

Here's one possible approach:

var sQuantity;
do {
  sQuantity = parseInt(prompt('Prompt message', 'Default prompt value'), 10);
} while (!sQuantity); 

The code shown in your question is wrong by two reasons. First, you don't actually check for sQuantity being equal to 0 - you assign 0 to it (with = 0; should've been == 0 at least). To be precise, actually assigned is the result of 0 || isNaN(sQuantity). And it's false - as sQuantity is equal to 0 at the moment of assignment, not NaN.

But even more important is the second flaw: there's no sense checking for sQuantity value with if right after you assigned a some value to it. You do know that it's equal to 0, right?

The only case when it makes sense is when you use a loop: first assigning some value to the variable (as result of prompt), then checking this value in the loop's condition.

In my example I've used do-while loop, as you obviously have to show prompt to a user at least once. With !sQuantity clause I check for both NaN and 0: these are the only falsy values that could be returned by parseInt.

OTHER TIPS

Shortest working code I can make:

var nbr;
while (isNaN(nbr = prompt("message", "test")));

Fiddle: http://jsfiddle.net/rh2Uq/1/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top