15.04.2018 Views

programming-for-dummies

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Branching Statements 491<br />

To make the computer choose between two mutually exclusive sets of commands,<br />

you can use an IF-ELSE statement, such as<br />

Book V<br />

Chapter 3<br />

if (condition) {<br />

Command;<br />

}<br />

else {<br />

Command;<br />

}<br />

JavaScript<br />

As an alternative to the IF-ELSE statement, you can also use the SWITCH<br />

statement to offer two or more choices, such as<br />

switch (expression) {<br />

case value1:<br />

Command;<br />

break;<br />

case value2:<br />

Command;<br />

break;<br />

default:<br />

Command;<br />

}<br />

The SWITCH statement always needs to include the break command to tell<br />

the computer when to exit out of the SWITCH statement.<br />

The above SWITCH statement is equivalent to the following IF-ELSE<br />

statement:<br />

if (expression = value1) {<br />

Command;<br />

}<br />

else if (expression = value2) {<br />

Command;<br />

}<br />

else {<br />

Command;<br />

}<br />

To check if a variable matches multiple values, you can stack multiple case<br />

statements, such as<br />

switch (expression) {<br />

case value1:<br />

case value2:<br />

Command;<br />

break;

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!