JavaScript 1.3 Overview, Part II: The Strict Equality Operators - Doc JavaScript | WebReference

JavaScript 1.3 Overview, Part II: The Strict Equality Operators - Doc JavaScript


The Strict Equality Operators

JavaScript 1.3 introduces two new operators, the strict equality operators. The strict equality operators (=== and !==) perform equality comparisons on operands of the same type. No type conversion is performed before the comparison. They should be both Integer, String, or any other JavaScript type:

operand1 === operand2
operand1 !== operand2

Use the strict equality operator (===) when you want to check that the two operands are of the same type and value. Use the regular equality operator (==) if you care only about the value and the type does not matter. If, for example, one operand is the number 5 and the other operand is the string "5", standard equality operator will return true, but, since they are not of the same type, a strict equality operator will return false.

Comparing two operands may be tricky at times. Comparing numbers is probably the most straightforward. Numbers are equal when they are numerically equal, or to put it differently, the difference between them is zero. Strings are compared according to a standard lexicographical ordering, using Unicode values (see our previous column, JavaScript 1.3 Overview, Part I). Therefore, two strings are equal when they have the same length, same sequence of characters, exactly in the same corresponding positions. The number NaN (see our previous column) is not equal to anything, including itself. Positive and negative zeros are equal.

Two objects are equal if they refer to the exact same Object. In the assembly line example from our previous page, we use the following line to construct the volvoInterior object:

volvoInterior = new interior("blue", "leather", true);

If we duplicate this line to construct two seemingly-identical objects, volvoInterior1 and volvoInterior2:

volvoInterior1 = new interior("blue", "leather", true);
volvoInterior2 = new interior("blue", "leather", true);

a strict equality operator:

if (volvoInterior1 === volvoInterior2)

will yield false. Only when objects are identical, will the strict equality operator return true:

if (volvoInterior1 === volvoInterior1)

But this behavior of object comparison is valid for standard equality operator as well. The comparison:

if (volvoInterior1 == volvoInterior2)

returns false, while the following operation:

if (volvoInterior1 == volvoInterior1)

returns true.

Comparing a string with a number highlights the difference between strict equality and standard equality operators.

if (5 === "5")

returns false, while the following test:

if (5 == "5")
returns true.

Boolean operands are equal if they are both true or false.

https://www.internet.com


Created: September 28, 1998
Revised: September 28, 1998

URL: https://www.webreference.com/js/column26/stricteq.html