Javascript if-else

Change program logic flow by using a conditional statement - 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.

if (condition1) { statementsA; (one or more statements) } else if (condition2) { statementsB; (one or more statements) } else { statementsC; (one or more statements) } statementsD;

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.

<script language="JavaScript"> <!-- Hide JavaScript code from old browsers var divisor = 10; var number = 100; var answer; // test the value of the divisor if (divisor == 0) { document.writeln("error. divisor equal to 0"); } else { answer = number/divisor; document.writeln(answer); } document.writeln("<br>" + "The divisor is " + divisor); // end hiding code --> </script>


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.

switch (expression) { case label : statements; break; case label : statement; break; ... default : statement; }

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.

var fruit = "apple"; switch (fruit) { case "apple" : document.writeln("An " + fruit + " is red."); break; case "bananna" : document.writeln("An " + fruit + " is yellow."); break; default : document.writeln("What color is your fruit?"); break; }

Intro         • Variables         • Statements         • If then else

Loops         • Objects         • Functions

Home   |   Business Directory   |   Festivals and Fairs (USA)