Understanding JavaScript Comparison Operators: Equality

The primary difference between arithmetic and comparison operators is that comparison operators don’t change values; instead, they compare them, producing a true or false evaluation. As such, they are frequently used in branching decisions, such as if conditions.

In comparisons, equality operators compare two operands, checking if they are equal or not. The greatest source of confusion for new coders usually lies in the first two of these:

== “is equal to”

Compares two operands to determine if they are equal. In the console:

 var firstVar = 2; var secondVar = 4 / 2; firstVar == secondVar;  > true

The equality operator is very often confused with the basic = assignment operator, especially by new coders. The easiest way to remember the difference is that a single = sets a value; using two (==) compares values.

Especially for new coders, this is further confused by a related comparison operator:

=== “is strictly equal to”

The basic equality operator has a problem, one easily shown in the console:

 2 == "2" > true

The equality comparison operator doesn’t compare types; in fact, it converts values to the same type before comparison. This can lead to serious problems in code: “lenient” comparisons allow true results from comparing values that are not strictly the same. But the strict comparison operator (sometimes called the identity operator) offers no space in which to hide:

 2 === "2" > false  2 === 2 > true

Dr. Axel Rauschmayer has argued that coders should always use strict comparisons, and I tend to agree, although it can be challenging to change habits if you have been coding “leniently” for some time.

!= “is not equal to”

The inequality operator is the functional opposite of the equality operator, the inequality operator returns true if the operands are not equal; like the equality operator, it converts type before comparison:

 var fallCarthage = -149; var catoYounger = -46;  fallCarthage != catoYounger > true  2 != "2" > false

Because of potential confusions like the second case above, the strict inequality comparison operator is usually recommended instead.

!== “is strictly not equal to”

Also known as the non-identity operator; returns true if the compared operands are not equal or not of the same type.

 var num = 3; var apt = "3";  num !== apt > true  var yearBorn = 1968; var manOnMoon = 1968; yearBorn !== manOnMoon; > false 

For a strict comparison between strings to be true, they must have the same length, and consist of the same characters in the same order.

Photograph by Bertalan Szürös, used under a Attribution-NonCommercial-NoDerivs 2.0 Generic Creative Commons license.

Leave a comment

Your email address will not be published.