Learn How to Program Using Any Web Browser
If statements are used to conditionally execute, or process, code. The conditional code is only executed if the condition evaluates to the Boolean value true.
JavaScript has three forms of the if statement. The first is simply as follows:
if (condition) statement;
In this form of the if statement, the statement executes if the condition is true.
The second form adds an else statement. The else statement executes if the condition is false (implying that the first statement hasn’t been executed):
if (condition) statement 1; else statement 2;
It’s important to understand that any statement within an if statement can be replaced by multiple statements using curly braces to create statement blocks as explained toward the end of Chapter 2, “ Understanding Types, Variables, and Statements.”
In general, it’s good programming practice to use curly braces with your if statements to make them easier to read and unambiguous. Using curly braces, the second form of the if statement would look like this:
if (condition) { statement 1; ... statement n; } else { statement n+1; ... statement n+m; }
Who is George Boole, and why name the Boolean value type after him? Boole, a nineteenth-century British mathematician, formulated an “algebra of logic” that can be used to mathematically calculate logical values using equations such as X = 1 to mean that the proposition X is true and X = 0 to mean that X is false. The 1 and 0 used in these logical equations is analogous to the true and false values used in modern programming languages.
The third form of the if statement adds else if clauses. You can use this when you have multiple conditions you need to cover. The general form is as follows:
if (condition) { statement 1; ... statement n; } else if (condition2) { statement n+1; ... statement n+m; } else if (condition3) { statement n+m; ... statement n+m+q; } else { // all the other conditions have failed statements; }
The equivalent processing could have been achieved without the else if statement using nested if else statements. (As an exercise, try and see how this is so!) However, else if makes the statement clearer and less likely to contain bugs.
To Create an If Statement:
Do it Right! |
|
Tip | It might seem easier to cobble if statements together on an ad-hoc basis without first creating the scaffolding. But as these statements get complex, you’ll find you save a great deal of time by creating the structure of the statement first. |
Категории