Comparisons
This short program will let you experiment with comparisons:
<html>
<!-- Comparisons -->
<head>
<title> Comparisons </title>
</head>
<body>
<!-- There's no need for a body at all -->
<script>
first = prompt("Enter a number:", "")
second = prompt("Enter another number:", "")
firstNumber = parseInt(first)
secondNumber = parseInt(second)
result = firstNumber > secondNumber
document.write (first + " > " + second + " is " + result)
</script>
</body>
</html>
Run the program and enter two numbers - we'll talk about comparing strings
later.
The ">" symbol means "greater than" so if you enter "1" and "2" into the two
prompts then you should see "1 > 2 is false" as the output. If you enter
"2" and "1" then you should see "2 > 1 is true".
Boolean values
We've already seen numeric variables holding values like 1 and 2 and string
variables holding values like "Hello" and "Fred". In this
program the variable named "result" is holding Boolean values. These aren't the
strings "true" and "false" they are the Boolean values true and false.
Other comparisons
JavaScript supports other comparisons:
- > Greater than
- >= Greater than or equal to
- < Less than
- <= Less than or equal to
- != Not equal to
Try using some of these in the program instead of the > comparison.
Testing for
equality
is perhaps the most common comparison but it deserves a page of its own
because it causes problems.
Comparing strings
We now know that JavaScript can compare two numbers. Try the equals
program again with letters. Once again you may be surprised by the result
but with a bit of thought it all makes sense.
If you enter the same letter twice into the two prompts then you'll get a
result something like "a = a is false". Once again it looks as though
JavaScript can't do something very simple but the strange result is the
fault of our programming.
Look back at the program and you'll remember that we're using parseInt() to
convert the input into numbers before comparing them. If you enter alphabetic
characters into the prompt then parseInt will convert them to NaN. Neither value
here is numeric so the comparison is between NaN and NaN. The browser can't
possibly say whether these two values are equal. All that it knows is that
neither value is a number.
Remove the parseInt from the program and change the prompts like this:
<script>
first = prompt("Enter some text:", "")
second = prompt("Enter some more text:", "")
result = first == second
document.write (first + " = " + second + " is " + result)
</script>
You should now find that the program recognises when two letters are the same.
Try with some longer strings. Is the comparison case sensitive?
|