2.3 Testing Numeric Equality

NN 2, IE 3

2.3.1 Problem

You want to know whether two numeric values are equal (or not equal) before continuing processing.

2.3.2 Solution

Use the standard equality operator (= =) in a conditional statement:

if (firstNum =  = secondNum) {
    // OK, the number values are equal

Values on either side of the equality operator may be variables or numeric literals. Typical practice places the suspect value to the left of the operator, and the fixed comparison on the right.

2.3.3 Discussion

JavaScript has two types of equality operators. The fully backward-compatible, standard equality operator (= =) employs automatic data type conversion in some cases when the operands on either side are not of the same data type. Consider the following variable assignments:

var numA = 45;
var numB = new Number(45);

These two variables might contain the same numeric value, but they are different data types. The first is a number value, while the second is an instance of a Number object. If you place these two values on either side of an equality (= =) operator, JavaScript tries various evaluations of the values to see if there is a coincidence somewhere. In this case, the two variable values would show to be equal, and the following expression:

numA =  = numB

returns true.

But the other type of equality operator, the strict equality operator (= = =), performs no data type conversions. Given the variable definitions above, the following expression evaluates to false because the two object types differ, even though their payloads are the same:

numA =  == numB

If one equality operand is an integer and the other is the same integer expressed as a floating-point number (such as 4 and 4.00), both kinds of equality operators find their values and data types to be equal. A number is a number in JavaScript.

If the logic of your code requires you to test for the inequality of two numbers, you can use the inequality (!=) and strict inequality (!= =) operators. For example, if you want to process an entry for a special value, the branching flow of your function would be like the following:

if (parseInt(document.myForm.myTextBox.value) != 0) {
    // process entry for non-zero values

The same issues about data type conversion apply to the inequality and strict inequality operators as to their opposite partners.

2.3.4 See Also

Recipe 2.1 for converting between number and string value types.