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 (Page 2 of 6 )
The if structure executes a statement based on the value produced from a boolean expression. It's written in the following way:
if(boolean expression) statement;
If the boolean expression evaluates to true, the interpreter executes the statement, then continues executing the following script statements. If the boolean expression evaluates to false, the interpreter doesn't execute the statement and continue executing the following script statements. You must delimit the boolean expression in parentheses. If you don't, the interpreter generates an error like the following one (don't put a semicolon at the end of the boolean expression, as it's not a statement, and if you do that the interpreter generates the same error because it's expecting the parentheses).
You can execute more than one statement with the if structure (when the boolean expression evaluates to true, of course) by using the code block syntax. A code block is any number of statements surrounded by curly braces ({}). These statements are executed together or escaped together. So the if block will look like this:
Now if the boolean expression evaluates to true, the statements 1, 2 and 3 get executed, then the interpreter continues executing the following statements. If the boolean expression evaluates to false, however, the interpreter escapes the statement 1, 2 and 3 (I mean the if block) and continues executing the statements that follow in the script. Note that I have indented the statements using the tab key in order to make the block more readable. This is very useful, especially when we work with nested if/else statements (discussed shortly), so it's a good practice to indent your code blocks. Let's integrate the if statement into our prompt box example.