Press enter to skip the top menu

JavaScript

Decisions

Learning Outcomes

On completion of this section you will know how to:

Go to top

Introduction

In all aspects of life we make decisions. An example is: if the buses are running we shall go into town, otherwise we shall study. In programming we have to make decisions as well or to be more precise we shall tell the computer how to make decisions.

To demonstrate this we shall modify the way we calculate the tax. When introducing our first programme we had a simple flat tax rate of 25%, which was fine as far as learning how a basic programme worked. In this example we shall take a more realistic view of the payroll application. We will create a tax regime where if the gross is below 500 we have a flat 25% rate. On the other hand if the gross is more than 500 then we pay 25% on the first 500 and 33% or the remainder. A few examples will help to explain this further.

A gross of 460 will be taxed at 25% since it is less than 500 and thus the tax will be 25% of 460, which is 115. This will give a net of 345.

A gross of 600 is greater than 500 and so it will be taxed as 25% of 500 and 33% of the remainder. 25% of 500 will be 125. The remainder will be 600 - 500= 100. 33% of 100 is 33. Thus the total tax is 125 + 33 = 158.

One more example is a gross of 720. Again this will be taxed as 25% of the first 500 which gives us 125, and 33% of the remainder which is 720-500 = 220. 33% of 220 is 72.60. Thus the total tax will be 125 + 72.60 = 197.60.

Now let us see how we will implement this in our JavaScript programme.

Go to top

The if..else Construct

Looking at Listing 1 below we see that it is similar to the previous application we looked at in 'A basic JavaScript Program' Lines 3 to 4 and lines 11 to 13 are identical to their predecessors, but lines 6 to 9 are new.

These are the lines that control whether we calculate tax on a low flat rate of 25% or at the higher rate 125 plus 33% of the amount above 500. As they are the only new lines in the application we shall concentrate only on them.

Listing 1
                        function calculatePay()
                        {
                            sngHours=document.getElementById("Hours").value;
                            curRate=document.getElementById("Rate").value;
                            curGross=sngHours*curRate;
                            if(curGross < 500)
                              curTax=curGross * 0.25;
                            else
                              curTax=125 + (curGross - 500) * 0.33;
                            curNet=curGross - curTax;
                            document.getElementById("Gross").value=curGross;
                            document.getElementById("Tax").value=curTax;
                            document.getElementById("Net").value=curNet;
                        }
                    

Line 5 above calculates the gross and stores the value in the variable curGross. In line 6 the body of our if construct starts with

if(curGross < 500)

The construct starts with the keyword if, which is followed by the condition inside brackets, i.e. (curGross < 500). This condition can be either true or false. As an example if curGross has a value of 400 then the condition is true, whereas if curGross has a value of 700 then the condition is false.

If the condition is true, i.e. if curGross has a value of 400, then the body of the if is executed, which only consists of line 7. In this line tax is calculated as 25% of the gross. Once the line has finished execution the else at line 8 and the body of the else at line 9 are skipped and control jumps to line 10 where the net is calculated.

On the other hand if the value of curGross is 700 then the condition at line 6 is false. In this case the body of the if is skipped and control passes down to line 9, i.e. the body of the else, where tax is calculated as 125 + 33 % of 200, giving 191.

In our example the body of the if and the body of the else had only one command line each. How would we deal with it if both bodies had more than one command line. The diagram below shows how this would be handled.

command 1

if(condition)

{

command 2

command 3

}

else

{

command 4

command 5

}

command 6

As can be seen the group of commands in the body of the if are enclosed between curly brackets. Thus if the condition is true the body of the if is executed, i.e. command 2 and command 3. Then program control skips to command 6.

If the condition is false then command 2 and command 3 are skipped and command 4 and command 5 are executed. Program flow then flows naturally to command 6.

Below is a sample output from our JavaScript code.

Go to top

The switch Construct

The if..else construct is fine when we have a yes/no situation, or in other words when we have only two choices. Although it can handle multiple choices, its structure can become very awkward. In order to avoid this we use the more elegant switch construct.

In order to explore this new construct we shall extend and alter our payroll application to include the calculation of superannuation. As well as entering the values of the hours worked and the hourly rate, the user will also enter a superannuation code. This code determines the percentage of the gross that will be deducted as superannuation. The table below shows the relationship between the code and the percentage.

CodePercentage
00
15
210
315
420

In order to accommmodate this change in the payroll processing, some changes will need to be made to both the form layout and the JavaScript code.

Two more fields will need to be added to the form: one for entering the superannuation code and another for displaying the superannuation amount.

For the JavaScript code a new technique must be employed to determine the correct percentage to apply when calculating the superannuation.

There is no change in the layout of the forms and therefore there is no need to alter the CSS file.

The HTML markup for the form is shown below. The additional code is shown bold.

Listing 2
                        <!doctype html>
                        <html lang="en">
                            <head>
                                <link href="Forms.css" rel="stylesheet" type="text/css">
                                <script src="Switch.js" type='text/javascript'></script>
                            </head>
                            <body>
                                <main>
                                   <a id="TopOfMain"></a>
                                    <form>
                                        <legend>All fields marked with * are required<br>Fields with shadowed backgrounds are in error</legend>
                                        <fieldset>
                                            <p>
                                                <label for="Hours">Hours Worked *</label><input type="number" id="Hours" name="Hours" min = "10" max="60" value="40" required>
                                            </p>
                                            <p>
                                                <label for="Rate">Hourly Rate *</label><input type="number" id="Rate" name="Rate" min="20" max="80" value="30" required >
                                            </p>
                                            <p>
                                                <label for="SRate">Super Rate *</label><input type="number" id="SRate" name="SRate" min="0" max="4" value="1" required >
                                            </p>
                                            <p>
                                                <label for="Gross">Gross</label><input type="text" name="Gross" id="Gross" disabled  >
                                            </p>
                                            <p>
                                                <label for="Tax">Tax</label><input type="text" name="Tax" id="Tax" disabled >
                                            </p>
                                            <p>
                                                <label for="Super">Super Amt</label><input type="text" name="Super" id="Super" disabled >
                                            </p>
                                            <p>
                                                <label for="Net">Net</label><input type="text" name="Net" id="Net" disabled >
                                            </p>
                                        </fieldset>
                                        <input type="button" value="Calculate Pay"  onclick="calculatePay()">
                                    </form>
                                </main>
                            </body>
                        </html>
                    

The change in the form itself is fairly minor. We need to add two label/input fields at lines 20 and 29. Our first pair is for entering the superannuation rate and the other is for displaying the amount that is to be contributed towards superannuation.

The bigest change is to the JavaScript code shown below in Listing 3. It is three times the length of its predecessor in Listing 1 avove.

Listing 3
                        function calculatePay()
                        {
                            sngHours=document.getElementById("Hours").value;
                            curRate=document.getElementById("Rate").value;
                            intSuperCode=document.getElementById("SRate").value;
                            switch(intSuperCode)
                            {
                                case '0':
                                    sngSuperRate=0;
                                    break;
                                 case '1':
                                    sngSuperRate=0.05;
                                    break;
                                case '2':
                                    sngSuperRate=0.1;
                                    break;
                                case '3':
                                    sngSuperRate=0.15;
                                    break;
                                case '4':
                                    sngSuperRate=0.2;
                                    break;
                               default:
                                   sngSuperRate=-1;
                            }
                            if(sngSuperRate==-1)
                                alert("Super code must be an integer in the range 0 - 4");
                            else
                            {     
                                curGross=sngHours*curRate;
                                if(curGross < 500)
                                    curTax=curGross * 0.25;
                                else
                                    curTax=125 + (curGross - 500) * 0.33;
                                curSuperAmt=curGross * sngSuperRate;
                                curNet=curGross - curTax - curSuperAmt;
                                document.getElementById("Gross").value=curGross;
                                document.getElementById("Tax").value=curTax;
                                document.getElementById("Super").value=curSuperAmt;
                                document.getElementById("Net").value=curNet;
                            }
                        }
                    

The extra code spans lines 5 to 29. At line 5 the value stored in the textbox SRate on the form is read and stored in the variable intSuperCode

Now the programme must determine which number was entered by the user in the input box, and, depending on that number, what value we are going to give to the superannuation rate, using Table 1 above as a guide.

The testing of the variable intSuperCode begins at line 6 with the command

switch(intSuperCode)

This is equivalent to saying 'test the value of the variable intSuperCode'. So how are we going to test it and what are we going to do with the result of our test? This is determined inside the body of the switch which spans lines 6 – 25.

At line 15 the command case ‘0’: is equivalent to 'if intSuperCode is equal to zero. If it is then control passes to line 16, where sngSuperRate is set to zero'. The keyword break at line 10 instructs programme control to jump to line 26, or in other words to jump out of the body of the switch.

Why do we need to jump out of the body of the switch once we have found a match? The reason is that if intSuperCode had a value of zero then line 16 would be activated. Once program control gets inside the case construct it stays there and lines 12, 15, 18, 21 and 24 would be executed. Thus intSuperRate would always end up with a value of -1.

If the value of intSuperCode was 1 then line 8 would be tested, but since a match was not found control would pass to line 11. Here a match is found and thus line 12 is executed, giving sngSuperRate a value of 0.05. Next the break at line 13 would be executed causing programme control to jump to line 26.

The same logic applies to other values of intSuperCode.

Finally what is the purpose of the default keyword at line 23? Its purpose is to trap values outside the accepted range. As an example, if the user entered 9 for the super code then the variable intSuperCode would have a value of 9. This is outside the range of acceptable values and therefore it will not be caught at any of the lines 8, 11, 14, 17 or 20. At line 23, however default will catch it which means that line 24 is executed, giving a value of -1 to sngSuperRate.

Naturally once line 24 is executed, control leaves the body of the switch construct and line 26 is executed. This is the first line of an if..else construct. The value of sngSuperRate is tested against -1. If this is correct it means that an invalid value has been entered for the superannuation code. Line 27 will then be executed which simply displays an error message and then finished program execution.

If, however, sngSuperRate is not -1 then the body of the else is executed, which means that the rest of the payroll calculation proceeds as normal.

Below is a sample output from the piece of code.

Go to top