HTML and CSS Reference
In-Depth Information
expression that determines whether a block of expressions will be executed. If the con-
dition after the
if
is met, the result is true, and the following block of statements is exe-
cuted; otherwise the result is false and the block is not executed.
FORMAT
if (condition){
statements;
}
EXAMPLE
if ( age > 21 ){
alert("Let's Party!");
}
The block of statements (or single statement) is enclosed in curly braces. Normally,
statements are executed sequentially. If there is only one statement after the conditional
expression, the curly braces are optional.
“You better pay attention now, or else . . . ” Ever heard that kind of statement before?
JavaScript statements can be handled the same way with the
if/else
branching construct.
This construct allows for a two-way decision. The
if
evaluates the expression in paren-
theses, and if the expression evaluates to true, the block after the opening curly braces
is executed; otherwise the block after the
else
is executed.
FORMAT
if (condition){
statements1;
}
else{
statements2;
}
EXAMPLE
if ( x > y ){
alert( "x is larger");
}
else{
alert( "y is larger");
}