Don’t Fear the Evil Twins (the == and != Operators)

Jeff Friesen

JavaScript developer Douglas Crockford has referred to JavaScript’s == and != operators as evil twins that should be avoided. However, once you understand them, these operators aren’t that bad and can actually be useful. This article examines == and !=, explains how they work, and helps you get to know them better.

The Problematic == and != Operators

The JavaScript language incorporates two sets of equality operators: === and !==, and
== and !=. Understanding why there are two sets of equality operators and figuring out which ones to use in which situations has been a source of much confusion.

The === and !== operators aren’t difficult to understand. When both operands are of the same type and have the same value, === returns true, whereas !== returns false. However, when the values or types differ, === returns false and !== returns true.

The == and != operators behave the same way when both operands have the same type. However, when the types differ, JavaScript coerces an operand to another type to make the operands compatible before comparing. The results are often confusing, as demonstrated below:

"this_is_true" == false // false
"this_is_true" == true  // false

Because there are only two possible Boolean values, you might think that one of the expressions should evaluate to true. However, they both evaluate to false. Additional confusion occurs when you assume transitive relations (if a equals b and b equals c then a equals c) should apply:

'' == 0   // true
0 == '0' // true
'' == '0' // false

This example reveals that == lacks transitivity. If the empty string equals the number 0, and if the number 0 equals the string consisting of the character 0, then the empty string should equal the string consisting of 0. But it doesn’t.

When faced with incompatible types while comparing operands via == or !=, JavaScript coerces one type to another to make them comparable. In contrast, it never performs type coercion (which leads to somewhat better performance) when using === and !==. Because of different types, === always returns false in the second example.

Understanding the rules that govern how JavaScript coerces an operand to a different type so that both operands are type-compatible before == and != are applied can help you determine when it’s more appropriate to use == and !=, and to feel confident using these operators. In the next section, we’ll explore the coercion rules that are used with the == and != operators.

How Do == and != Work?

The best way to learn how == and != work is to study the ECMAScript Language Specification. This section focuses on ECMAScript 262. Section 11.9 of the spec addresses the equality operators.

The == and != operators appear in grammar productions EqualityExpression and EqualityExpressionNoIn. (Unlike the first production, the second production avoids the in operator.) Let’s examine the EqualityExpression production, shown below.

EqualityExpression :
   RelationalExpression
   EqualityExpression == RelationalExpression
   EqualityExpression != RelationalExpression
   EqualityExpression === RelationalExpression
   EqualityExpression !== RelationalExpression

According to this production, an equality expression is either a relational expression, an equality expression equal to a relational expression via ==, an equality expression not equal to a relational expression via !=, and so on. (I ignore === and !==, which aren’t relevant to this article.)

Section 11.9.1 presents the following information on how == works:

The production EqualityExpression : EqualityExpression == RelationalExpression is evaluated as follows:

  1. Let lref be the result of evaluating EqualityExpression.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating RelationalExpression.
  4. Let rval be GetValue(rref).
  5. Return the result of performing abstract equality comparison rval == lval. (See 11.9.3.)

Section 11.9.2 presents similar information on how != works:

The production EqualityExpression : EqualityExpression != RelationalExpression is evaluated as follows:

  1. Let lref be the result of evaluating EqualityExpression.
  2. Let lval be GetValue(lref).
  3. Let rref be the result of evaluating RelationalExpression.
  4. Let rval be GetValue(rref).
  5. Let r be the result of performing abstract equality comparison rval != lval. (See 11.9.3.)
  6. If r is true, return false. Otherwise, return true.

lref and rref are references to the left and right sides of the == and != operators. Each reference is passed to the GetValue() internal function to return the corresponding value.

The heart of how == and != work is specified by the Abstract Equality Comparison algorithm, which is presented in Section 11.9.3:

The comparison x == y, where x and y are values, produces
true or false. Such a comparison is performed as follows:

  1. If Type(x) is the same as Type(y), then
    1. If Type(x) is Undefined, return true.
    2. If Type(x) is Null, return true.
    3. If Type(x) is Number, then
      1. If x is NaN, return false.
      2. If y is NaN, return false.
      3. If x is the same Number value as y, return true.
      4. If x is +0 and y is -0, return true.
      5. If x is -0 and y is +0, return true.
      6. Return false.
    4. If Type(x) is String, then return true if x and y are exactly the same sequence of characters (same length and same characters in corresponding positions). Otherwise, return false.
    5. If Type(x) is Boolean, return true if x and y are both true or both false. Otherwise, return false.
    6. Return true if x and y refer to the same object. Otherwise, return false.
  2. If x is null and y is undefined, return true.
  3. If x is undefined and y is null, return true.
  4. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
  5. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
  6. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
  7. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
  8. If Type(x) is either String or Number and Type(y) is Object, return the result of the comparison x == ToPrimitive(y).
  9. If Type(x) is Object and Type(y) is either String or Number, return the result of the comparison ToPrimitive(x) == y.
  10. Return false.

Step 1 in this algorithm executes when the operand types are the same. It shows that undefined equals undefined and null equals null. It also shows that nothing equals NaN (Not a Number), two identical numeric values are equal, +0 equals -0, two strings with the same lengths and character sequences are equal, true equals true and false equals false, and two references to the same object are equal.

Steps 2 and 3 show why null != undefined returns false. JavaScript considers these values to be the same.

Beginning with Step 4, the algorithm becomes interesting. This step focuses on equality between Number and String values. When the first operand is a Number and the second operand is a String, the second operand is converted to a Number via the ToNumber() internal function. The expression x == ToNumber(y) indicates recursion; the algorithm beginning in Section 11.9.1 is reapplied.

Step 5 is equivalent to Step 4 but the first operand is of type String and must be converted to a Number type.

Steps 6 and 7 convert a Boolean operand to Number type and recurse. If the other operand is Boolean, it will be converted to a Number on the next execution of this algorithm, which will recurse one more time. From a performance perspective, you might want to ensure that both operands are of Boolean type to avoid both recursion steps.

Step 9 reveals that if either operand is of Object type, this operand is converted to a primitive value via the
ToPrimitive() internal function and the algorithm recurses.

Finally, the algorithm considers both operands unequal and returns false in Step 10.

Although detailed, the Abstract Equality Comparison algorithm is fairly easy to follow. However, it refers to a pair of internal functions, ToNumber() and ToPrimitive(), whose inner workings need to be exposed to have a complete understanding of the algorithm.

The ToNumber() function converts its argument to a Number, and is described in Section 9.3. The following list summarizes possible nonnumeric arguments and equivalent return values:

  • If the argument is Undefined then return NaN.
  • If the argument is Null then return +0.
  • If the argument is Boolean true then return 1. If the argument is Boolean false then return +0.
  • If the argument has Number type then the input argument is returned — there is no conversion.
  • If the argument has String type then Section 9.3.1 “ToNumber Applied to the String Type” applies. A numeric value corresponding to the string argument as indicated by the grammar is returned. If the argument doesn’t conform to the indicated grammar, NaN is returned. For example, argument "xyz" results in NaN being returned. Also, argument "29" results in 29 being returned.
  • If the argument has Object type then apply the following steps:
    1. Let primValue be ToPrimitive(input argument, hint Number).
    2. Return ToNumber(primValue).

The ToPrimitive() function takes an input argument and an optional PreferredType argument. The input argument is converted to a non-Object type. If an object is capable of converting to more than one primitive type, ToPrimitive() uses the optional PreferredType hint to favor the preferred type. Conversion occurs as follows:

  1. If the input argument is Undefined then the input argument (Undefined) is returned — there is no conversion.
  2. If the input argument is Null then the input argument (Null) is returned — there is no conversion.
  3. If the input argument has Boolean type then the input argument is returned — there is no conversion.
  4. If the input argument has Number type then the input argument is returned — there is no conversion.
  5. If the input argument has String type then the input argument is returned — there is no conversion.
  6. If the input argument has Object type then a default value corresponding to the input argument is returned. The default value of an object is retrieved by calling the object’s [[DefaultValue]] internal method passing the optional PreferredType hint. The behaviour of [[DefaultValue]] is defined for all native ECMAScript objects in Section 8.12.8.

This section presented a fair amount of theory. In the next section, we’ll move to the practical by presenting various expressions involving == and != and walking through the algorithm steps to evaluate them.

Getting to Know the Evil Twins

Now that we know how == and != work according to the ECMAScript specification, let’s put this knowledge to good use by exploring various expressions involving these operators. We’ll step through how these expressions are evaluated and discover why they are true or false.

For my first example, consider the following pair or expressions that were presented near the beginning of the article:

"this_is_true" == false // false
"this_is_true" == true  // false

Follow these steps the evaluate these expressions according to the Abstract Equality Comparison algorithm:

  1. Skip Step 1 because the types are different: typeof "this_is_true" returns "string" and typeof false or typeof true returns "boolean".
  2. Skip steps 2 through 6, which don’t apply because they don’t match the operand types. However, Step 7 applies because the right argument is of type Boolean. The expressions are converted to "this_is_true" == ToNumber(false) and "this_is_true" == ToNumber(true).
  3. ToNumber(false) returns +0 and ToNumber(true) returns 1, which reduces the expressions to "this_is_true" == +0 and "this_is_true" == 1, respectively. At this point the algorithm recurses.
  4. Skip steps 1 through 4, which don’t apply. However, Step 5 applies because the left operand is of type String and the right operand is of type Number. The expressions are converted to ToNumber("this_is_true") == +0 and ToNumber("this_is_true") == 1.
  5. ToNumber("this_is_true") returns NaN, which reduces the expressions to NaN == +0 and NaN == 1, respectively. At this point, the algorithm recurses.
  6. Step 1 is entered because each of NaN, +0, and 1 are of type Number. Steps 1.a and 1.b are skipped because they don’t apply. However, Step 1.c.i applies because the left operand is NaN. The algorithm now returns false (NaN isn’t equal to anything including itself) as the value of each original expression and rewinds the stack to fully exit the recursion.

My second example (which is based on the meaning of life according to The Hitchhiker’s Guide to the Galaxy) compares an object to a number via ==, returning a value of true:

var lifeAnswer = {
  toString: function() {
    return "42";
  }
};

alert(lifeAnswer == 42);

The following steps show how JavaScript uses the Abstract Equality Comparison algorithm to arrive at true as the expression’s value:

  1. Skip steps 1 through 8, which don’t apply because they don’t match the operand types. However, Step 9 applies because the left operand is of type Object and the right operand is of type Number. The expression is converted to ToPrimitive(lifeAnswer) == 42.
  2. ToPrimitive() calls lifeAnswer‘s [[DefaultValue]] internal method without a hint. According to Section 8.12.8 in the ECMAScript 262 specification, [[DefaultValue]] calls the toString() method, which returns "42". The expression is converted to "42" == 42 and the algorithm recurses.
  3. Skip steps 1 through 4, which don’t apply because they don’t match the operand types. However, Step 5 applies because the left operand is of type String and the right operand is of type Number. The expression is converted to ToNumber("42") == 42.
  4. ToNumber("42") returns 42, and the expression is converted to 42 == 42. The algorithm recurses and Step 1.c.iii executes. Because the numbers are the same, true is returned and the recursion unwinds.

For my final example, let’s figure out why the following sequence doesn’t demonstrate transitivity in which the third comparison would return true instead of false:

'' == 0   // true
0 == '0' // true
'' == '0' // false

The following steps show how JavaScript uses the Abstract Equality Comparison algorithm to arrive at true as the value of '' == 0.

  1. Step 5 executes resulting in ToNumber('') == 0, which converts to 0 == 0 and the algorithm recurses. (Section 9.3.1 in the specification states that The MV [mathematical value] of StringNumericLiteral ::: [empty] is 0. In other words, the numeric value of the empty string is 0.)
  2. Step 1.c.iii executes, which compares 0 with 0 and returns true (and unwinds the recursion).

The following steps show how JavaScript uses the Abstract Equality Comparison algorithm to arrive at true as the value of 0 == '0':

  1. Step 4 executes resulting in 0 == ToNumber('0'), which converts to 0 == 0 and the algorithm recurses.
  2. Step 1.c.iii executes, which compares 0 with 0 and returns true (and unwinds the recursion).

Finally, JavaScript executes Step 1.d in the Abstract Equality Comparison algorithm to arrive at true as the value of '' == '0'. Because the two strings have different lengths (0 and 1), false is returned.

Conclusion

Perhaps you’re wondering why you should bother with == and !=. After all, previous examples have shown that these operators can be slower than their === and !== counterparts because of type coercions and recursion. You might want to use == and != because there are contexts where === and !== offer no advantage. Consider the following example:

typeof lifeAnswer === "object"
typeof lifeAnswer == "object"

The typeof operator returns a String value. Because a String value is being compared to another String value ("object"), no type coercion takes place and == is just as efficient as ===. Perhaps newcomers to JavaScript who’ve never encountered === will find such code clearer. Similarly, the following code fragment requires no type coercion (both operands have Number type) and so != is no less efficient than !==:

array.length !== 3
array.length != 3

These examples suggest that == and != are appropriate in comparisons that require no coercions. When the operand types are different, === and !== are the way to go because they return false rather than unexpected values (e.g., false == "" returns true). If the operand types are the same, there’s no reason not to use == and !=. Perhaps it’s time to stop fearing the evil twins, which aren’t so evil after you get to know them.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • Jingqi Xie

    There is no transitivity in the != operator. Thanks.

  • jokeyrhyme

    Wow, these are complicated! I think I’ll follow Douglas Crockford’s lead here and avoid these like the plague.

    Even for the case where no coercion is necessary, it seems like it would be safer to follow his advice as a general rule.

    Great article though, very enlightening. :)

  • g00glen00b

    I might be wrong, but your conclusion with != not being transitive (second example) is odd. You say that if A != B and B != C then A != C. Well, let’s say that A is 2, B is 3 and C is 2, then: 2 != 3, 3 != 2 but 2 != 2 is false. You should never conclude that if A != B and B != C that A != C, it doesn’t say anything about A and C, except that they can be anything except B.

  • Hervé Tatche

    It seems to me way too complicate, but we are used to javascript oddity aren’t we ? I will start using === and !== from now on to avoid problems. Anyway, “0″ should never be equal to 0, even if javascript has dynamic types.

    Very good and extensive article !

  • Liam Le Brun

    Just feel I should point out, your algebra around the comparison between null, false and undefined is itself incorrect. This is more obvious when you rotate each of the statements so:

    null != false
    false != undefined
    null != undefined

    null == !false
    false == !undefined
    null == !undefined

    The last line should be “null == !!undefined” or “null == undefined”.

  • Jeff Friesen

    I apologize to everyone for my mistake in assuming that the != operator should be transitive. I’ve notified my editor and the offending text will be removed from the article.

  • Ed Gauci

    Hmm, I don’t find “perhaps newcomers to javascript who have never encountered === will find such code clearer” to be a particularly compelling argument. I like the article, but I just don’t see any good reason to ever use == or !=.

  • http://anagrammatically.com Antonios Sarhanis

    The length and technical nature of this article is exactly why you should never use == or !=.

    All operators need to be simple and transparent. They’re the basis of code. Having to think through implicit type conversions for an operator is ridiculous.

    It doesn’t matter if you’re a newcomer or an old hand. Never using == or != will produce far fewer bugs.

  • https://socialinvaders.com/ Filip Sobczak

    Well, but then again there isn’t any reason listed to use ‘==’… so why would I use it? I find ‘==’ helpful where types are different – typically comparison of number with a string 5 == ’5′

  • CTN

    now write the tldr; version