the var rate of 1000 can't determine the string?

Viewed 13

When I input the BSIT in the prompt, the rate is always 1200 even though the string is correct

<html> <HEAD>
<TITLE> Simple Enrollment Computation </TITLE>
<SCRIPT language="JavaScript"> 
<!--hide  

alert('Hi, Welcome!');
var yourname = prompt('Please enter your name.');
var course = prompt('Enter your Course');
var units= prompt('Enter number of units:');
if ( (course = 'BSIT') || (course = 'bsit') )
{
    var rate = 1000
}
else ( (course == ' ') || (course == null) )
{
    var rate = 1200
}

var total=  rate * units
1 Answers

You have a bug in your code that throws the path of execution off.

An else clause never takes a condition - if the condition on the if evaluates to false, the else is executed - and in your code snippet that means that the test behind the else is evaluated. However, since the result is never assigned to anything, it is lost. The block right behind that is executed no matter what, thereby unconditionally setting rate to a value of 1200.

Original statement, with annotations and slightly reformatted:

if ( (course = 'BSIT') || (course = 'bsit') )
{
// Will be executed when course == 'BSIT' or 'bsit'
    var rate = 1000
}
// If course == ' ' or null, else is invoked, and since the condition
// is directly following the else, that is evaluated.
else 
    ( (course == ' ') || (course == null) )
// The following block is NOT attached to the else and so gets executed
// no matter what!
{
    var rate = 1200
}

Your best bet would be to either put an if right behind the else (this way the condition has an effect, and the previously dangling block becomes part of the second if statement) or change it into a switch statement.

Modified if statement:

var rate;      // One declaration is entirely sufficient.

if((course == 'BSIT') || (course == 'bsit'))
  {
  rate = 1000;
  }
else
  if((course == ' ') || (course == null))
    {
    rate = 1200;
    }

switch statement:

var rate;

switch(course)
  {
  case 'BSIT':
  case 'bsit':
    rate = 1000;
    break;

  case ' ':
  case null:
    rate = 1200;
    break;
  }

Each variant is going to fix that problem, however, you are going to wind up with an undefined value in rate if anything else than the expected values is entered. You should also account for that and assign a default value before doing any checks.

Related