Testing for equality
This short program tests whether two numbers are equal:
<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>
Try this and you'll not get the answers you expect. Let's take a closer
look at the line that's causing the problem:
result = firstNumber = secondNumber;
What on earth is the browser to make of this? We've used the equals sign
twice in this statement, the first time it means "assign a value to this
variable", the second time it means "are these equal?". The browser
can't be expected to read our minds so it just took "=" to mean "assign
a value." It read the value from secondNumber, stored it in firstNumber
and then stored it again in result.
In order to avoid this confusion, JavaScript uses a double equals sign
to mean "are these equal?" and the single equals sign only has the meaning
"assign a value to this variable". The line which we thought was a
comparison was really just an unusual way of assigning values.
Change the line to read:
result = firstNumber == secondNumber;
and it should work as you'd expect.
|