![]() Web Design Specialists. |
Javascript if-else
Change program logic flow by using a conditional statement - if-else. |
|
if-else
The if-else statement is one way of testing conditions in your program. Below you'll see the
format for using if-else. If condition A is true, statementsA will be performed. Then,
program flow will jump over all other else conditions and execute statementsD. If conditionA
is false, conditionB will be tested. If true, statementsB will be performed, after which
statementsD will be performed. If both conditionA and conditionB fail, statementsC will be
performed, then statementsD. You can have multiple else if conditions or can omit both the
else ifs and the else altogether.
Below you'll see an example of an if-else statement. Try changing the value of the divisor to see how the program behaves differently when it equals 0 or not.
switch
The switch performs similarly to the if-else statement. If you need to test a single
expression multiple times, it may be easier to the use the switch statement.
Below you'll see the format for the switch statement. expression is the variable you are
testing. label is the value of the variable you are testing for. statements are the
statements you wish to perform if the label tests true. When the break statement is executed,
all other case conditions will be skipped and normal program flow will continue with the
statements after the switch. The default statements will be performed if all the case labels
fail.
Below we have declared a variable fruit and set it equal to apple. The switch statement tests the value of this variable. Change the value of fruit and see how the switch statement behaves.
|
Intro
|
Variables
|
Statements
|
If then else
|
Loops
|
Objects
|
Functions
|
HOME