The Power of Javascript: Controlling the Execution of the Script
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.
The Power of Javascript: Controlling the Execution of the Script - The if statement example (Page 3 of 6 )
Copy the following code into an HTML document and save it.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title>Hello World</title> <script language="JavaScript" type="text/javascript"> var someText; someText = prompt("Please enter some text", "I like Javascript"); if(someText == "I like Javascript") alert("You have entered the default text"); document.write("This is the first statement after the if statement"); </script> </head> <body> </body> </html>
When you load the document into your Web browser the dialog box prompt will be displayed as in the previous example:
Don't change the default text and click on OK, a message box is displayed to tell you that you have entered the default text.
And the following line will be printed to the Web page:
Note that this line is written to the Web page whether the if statement's boolean expression evaluated to true or false, because in both cases the interpreter continued the execution of the first statement that followed the if statement. The boolean expression evaluates to true because the value "I like Javascript" is the same value of the variable someText, so that's why the message box is displayed. The document.write() line is not part of the if structure, but intentionally I have done that to explain how important it is to put the curly braces {} with the if statement (and to indent the blocks) so your code becomes more readable. It's better to write the example as follows:
<script language="JavaScript" type="text/javascript"> var someText; someText = prompt("Please enter some text", "I like Javascript"); if(someText == "I like Javascript") { alert("You have entered the default text"); } document.write("This is the first statement after the if statement"); </script>