Equality comparison in JavaScript:(==)&(===)

Overall, JavaScript have three differenct value-comparison operations:

  • == — loose equality;
  • === — strict equality;
  • Object.is() very uncommon usage.

Let’s look at the difference between these three operations:

  • === will compare two things without type conversion. which means the first step is check the type of two things.

    1. If typeof(x) is not typeof(y) then return false
    2. If x, y are Number then compare the value of those two number.
    3. Special case: NaN === NaN -> return false, +0 === -0-> return true, null === undefined -> return false.
  • == will do a type conversion when comparing two things;

    1. If typeof(x) is typeof(y) then compare value;
      • Object and Symbol: return true only when both operands reference the same object or same Symbol.
      • String: return true only when both operands have the same characters in same order;
      • Boolean, Number, BigInt, Symbol follow the same rule as bothe equal to another.
    2. Type conversion rule:
      • If one is Symbol another not, return false;
      • If one is Boolean another not, convert true to 1 and false to 0;
      • If one is String another is BigInt, convert String to BigInt using Bigint(), if conversion failed return false;
      • If one is String another is Number, convert String to BigInt using Number(), if conversion failed return false;
      • If one of the an object and other is a primitive, convert the object to a primitive;
    3. NaN == NaN and +0 == -0 is the same as ===, but null == undefined -> return true.
  • Object.is() is almost the same as strict equality ===, the diffrences are

    1. Object.is(NaN, NaN) // true;
    2. Object.is(+0, -0) // false;

The Usage of comparison operation

  1. Strict equality is almost always the correct comparison operation to use. Because it does not implement type conversion, so it is faster than loose equality;
  2. The built in methods including: Array.prototype.indexOf(), Array.prototype.lastIndexOf(), TypedArray.prototype.indexOf(), TypedArray.prototype.lastIndexOf() are all using strict euqality.
  3. When doing some legal check, undefined and null, using loose euqality is Ok.

Reference

  1. mdn web docs.(2023).Equality comparisons and sameness. Retrieved from https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
  2. ECMA262. (2023). https://tc39.es/ecma262/multipage/abstract-operations.html#sec-islooselyequal
comments powered by Disqus
© 2020 Lingyun Yang
Built with Hugo
Theme Stack designed by Jimmy