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.

MS Access technical tips

Visual FoxPro technical tips

General Tips

 

More tips from Alvechurch Data

Search page for Alvechurch Data

Searching a web site with JavaScript

Read More

Site Map

Site map of the Alvechurch Data site

Read More

Javascript while loops

JavaScript do and while loops

Read More

Javascript for loops

Javascript for loops

Read More

Repetition in Javascript

JavaScript structures for repetition

Read More