Today’s article is for those who have moved to JavaScript without having any previous programming experience. It discusses solutions to situations when we have to do different things depending on the value of a variable. The books usually assume that you already have the underlying concepts and they just show the syntax. Programming is an art and its almost independent of the technology being used. That’s why todays article is as valid for C++ as it is for JavaScript.

if-then-else

Multiple Choices

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

Make sure that you understand the above italicized text. We can’t go any further without understanding it. These three lines are in the form pseudocode in that they do not use any particular syntax. We are only listing a way to solve the problem, independent of any programming language. An if-then-else based JavaScript solution is given below:

<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>

Some Explanation

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.

As mentioned in the beginning, you can use the ideas presented here in any programming language. JavaScript is based on Java’s syntax which in turn is based on C++. An multiple if situation is not very difficult to handle, ask me if you don’t understand something.

Leave a Reply

Your email address will not be published.