Home

JavaScript Tutorial

9. If/Else Statements

if statements execute a set of commands if a specified condition is true. If the condition is false, another set of statements can be executed through the use of the else keyword.

The main idea behind if statements is embodied by the sentence: "If the weather's good tomorrow, we'll go out and have a picnic and Lisa will do cartwheels -- else, we'll stay in and Catherine will watch TV."

As you can see, the idea is quite intuitive and, surprisingly enough, so is the syntax:

if (condition) { statements1 } -or- if (condition) { statements1 } else { statements2 }

(An if statement does not require an else statement following it, but an else statement must be preceded by an if statement.)

condition can be any JavaScript expression that evaluates to true or false. Parentheses are required around the condition. If condition evaluates to true, the statements in statements1 are executed.

statements1 and statements2 can be any JavaScript statements, including further nested if statements. Multiple statements must be enclosed in braces.

Here's an example:

if (weather == 'good') { go_out(we); have_a_picnic(we); do_cartwheels(Lisa); } else { stay_in(we); watch_TV(Catherine); }