0

I am new to JavaScript and I wrote this small script and linked it to a regular HTML document so I could test it out. When opened, the page will prompt the user with "How many people in your lobby?", but no matter what you put as an answer, the document will only display "You have NaN players in your party!" Why does it only return NaN? I know that there are better ways to make a script that asks a user a number and verifies that the user wrote a number, but how come this particular script does not work? What did I do wrong?

'use strict';

var numberOfPlayers = prompt("How many people in your lobby?", 1);

if (numberOfPlayers = NaN) {
var numberOfPlayers = prompt("Sorry, please input a number. How many people in your lobby?", 1)
}

else if (numberOfPlayers < 0){
var numberOfPlayers = prompt("Sorry, please input a number bigger than 0. How many people in your lobby?", 1)
}

else {
}


document.write("You have " + numberOfPlayers + " players in your party!"); 
VLAZ
  • 26,331
  • 9
  • 49
  • 67
  • 2
    `=` is assignment. `==` or `===` are comparisons, but you need `isNaN` or `Number.isNaN` to check for actual `NaN` values. – VLAZ Apr 23 '21 at 16:36

1 Answers1

0

There are few issues in your code:

  1. You are using assignment (=) in the condition which evaluates the condition always true, for comparison you should either use == or ===.

  2. To check whether some value is a number or not you should use isNaN().

  3. You should also not redeclare the same variable again.

You can try the following way:

'use strict';

var numberOfPlayers = prompt("How many people in your lobby?", 1);
console.log(numberOfPlayers)
if (isNaN(numberOfPlayers)) {
  numberOfPlayers = prompt("Sorry, please input a number. How many people in your lobby?", 1)
}

else if (numberOfPlayers < 0){
  numberOfPlayers = prompt("Sorry, please input a number bigger than 0. How many people in your lobby?", 1)
}

else {
}


document.write("You have " + numberOfPlayers + " players in your party!");
Mamun
  • 66,969
  • 9
  • 47
  • 59