USER INPUT CONSIDERATIONS

Whenever you collect user input, you need to consider all the possibilities including what happens if a user doesn't enter anything. Even with a simple prompt to obtain a user's first name, there are at least three different possibilities for user input, such as the following:

  • The user enters a response, and clicks OK. The response is saved as a string.
  • The user doesn't enter anything; only clicks OK. The response is saved as an empty string.
  • The user enters a response, and then clicks Cancel. The response is saved as null, meaning a nonexistent value.

Remember that a prompt returns a string. If you want to do numerical calculations -- specifically addition -- with prompt data, you need to convert it from string data to numeric data; otherwise, JavaScript will concatenate the strings together rather than adding the numbers.

You can create variable responses to user input by setting up conditions, such as if and else. Conditions and loops are covered in Lesson 4.