When you write a script, most of the time you need to make a decision based on the values of some of your variables, or based on the values entered by the users, or even based on user actions. Decision making is a fundamental building block for all programming languages and it's similar in most of them. In this article, we discuss the if/else statement block, the switch statement, and take a look at the prompt() dialog box.
Interacting with the user
The dialog box prompt contains two buttons (OK and Cancel), one text box (where the user answers the question or enters the data), and a label that displays the question. In the above prompt box the question is "Do you like action movies?" There is a default answer in the text box, so you only need to change the value then click on OK. Let's look at an example and explain the possible values that can be produced (returned) from the prompt box. Copy the following code into your document file and save it, then load it into your browser.
When you load this code the browser displays the following prompt box.
The prompt() functionality takes two string values between the parentheses. The first value is the question to be displayed in the prompt box and the second value (which is optional and can be removed) is the default text of the text box. Note that we separate the two values inside the parentheses using the coma (,). We could include only the question to be displayed and remove the second value (the default text). In this case the prompt box will look like this prompt("Enter some text please");
In our example, the interpreter understands that we need to assign the variable someText a value at runtime (I mean at the time in which the script is running, that is, when you load the page into the browser), so it displays the prompt box. When the user clicks Ok it takes the value and stores it in the variable someText. Then the functionality document.write() writes the value of the variable someText to the Web page.
Let's take a look at what happens when the user clicks the Cancel button. Refresh the Web page and this time click on the Cancel button. You will get the value null written to the Web page as in the following figure.
So what's null? Why did the Interpreter assign this value to the variable someText? Null means nothing, which is not equal to an empty string like this "". Nothing means that there's no value at all. When you clicked the Cancel button, the interpreter understood that there's no return value from the prompt box, so it assigned the value null to the variable someText. We will discuss null in more detail; we will be using it a lot, so don't worry because you will understand how important it is to test on this value. In the following sections we are going to learn how to control the execution of our script's code and we will be extending our example.