So far in this book, we've seen how we can use JavaScript to get user input, perform calculations and tasks with that input, and write the results to a web page. However, a pocket calculator can do all this, so what is it that makes computers different? That is to say, what gives computers the appearance of having intelligence? The answer is the capability to make decisions based on information gathered.
How will decision making help us when creating websites? In the last chapter we wrote some code that converted temperature in degrees Fahrenheit to centigrade. We obtained the degrees Fahrenheit from the user using the prompt() function. This worked fine if the user entered a valid number, such as 50. If, however, the user entered something invalid for the Fahrenheit temperature, such as the string aaa, we find that our code no longer works as expected. Now, if we had some decision-making capabilities in our program, we could check to see if what the user has entered is valid. If it is, we can do the calculation, and if it isn't, we can tell the user why and ask him to enter a valid number.
Validation of user input is probably one of the most common uses of decision making in JavaScript, but it's far from being the only use. Our trivia quiz also needs some decision-making capabilities so that we can check if the answer given by the user is right or wrong. If it's right, we need to take certain steps, such as telling the user that she is right and increasing her score. If the answer is wrong, a different set of code needs to be executed to tell her that she's wrong.
In this chapter we'll look at how decision making is implemented in JavaScript and how we can use it to make our code smarter.