Syntax
Multiple
To see how this works, this is how it would look like if the nesting were properly indented:
To execute multiple statements within a clause, use a block statement (
Do not confuse the primitive boolean values
Example: Using
It is advisable to not use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code. For example, do not use the following code:
If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. For example:
if (condition) statement1 [else statement2]
Parameters
condition- An expression that evaluates to true or false.
statement1- Statement that is executed if
conditionevaluates to true. Can be any statement, including further nestedifstatements. To execute multiple statements, use a block statement ({ ... }) to group those statements.
statement2- Statement that is executed if
conditionevaluates to false and theelseclause exists. Can be any statement, including block statements and further nestedifstatements.
Description
Multiple
if...else statements can be nested to create an
else if clause:if (condition1) statement1 else if (condition2) statement2 else if (condition3) statement3 ... else statementN
To see how this works, this is how it would look like if the nesting were properly indented:
if (condition1)
statement1
else
if (condition2)
statement2
else
if (condition3)
...
To execute multiple statements within a clause, use a block statement (
{ ... }) to group those statements. In general, it is a good
practice to always use block statements, especially in code involving nested
if statements:if (condition) {
statements1
} else {
statements2
}
Do not confuse the primitive boolean values
true and
false with the true and false values of the Boolean object. Any value that is not
undefined, null, 0, NaN, or
the empty string (""), and any object, including a Boolean object
whose value is false, evaluates to true when passed to a conditional statement.
For example:var b = new Boolean(false); if (b) // this condition evaluates to true
Examples
Example: Using
if...else
if (cipher_char == from_char) { result = result + to_char; x++; } else { result = result + clear_char; }
Example: Assignment within the conditional expression
It is advisable to not use simple assignments in a conditional expression, because the assignment can be confused with equality when glancing over the code. For example, do not use the following code:
if (x = y) { /* do the right thing */ }
If you need to use an assignment in a conditional expression, a common practice is to put additional parentheses around the assignment. For example:
if ((x = y)) { /* do the right thing */ }
No comments:
Post a Comment