The switch statement is basically used to execute different sets of statements depending on a choice. For example, an income tax policy may state:
charge 10% for those earning less than $10,000 per annum; 20% for those earning less than $20,000 but more than $10,000 per annum; 30% for all others.
Below we will take this situation and present a solution.
Example (using if-then-else)
An if statement may have an optional else part. We can restate the above problem for programming convenience as,
if income < 10,000 then income tax = 10% of income
else if income < 20,000 then income tax = 20% of income
else income tax = 30% of income
<html> <head> <title>Multiple Choice Situations</title> </head> <body> Enter your income in the input box below: <form> <input type="text" size="25" name="income"> <input type="button" value="Calculate" onClick="calculateTax(income.value)"> </form> </body> </html>
You may not be familiar with a few things used above:
- We have used parseInt to convert a string into integer. Internally, these two things are represented quite differently. When you write your income as “10000”, its different from 10000. The former is a strings while the later is a number. To convert a string into number we can use parseInt(theString). We had to do this conversion because we can’t compare a string with numbers.
- We don’t need to enclose a statement after an if construct, if that is the single statement to be executed when the if condition is true.
- The button in the form that calls the function calculateTax passes income.value to the function. This is done because income is a textbox while the function works on a string. Doing parseInt on a textbox doesn’t make sense.