Operators and equality

JavaScript · Essentials · 10 min

Equality and coercion rules are the most common source of surprising results in JavaScript.

The arithmetic operators are + - * /, plus % (remainder) and ** (power). Each has a compound assignment form: x += 2, x **= 2, and ++/-- add or subtract one.

+ is special: if either operand is a string, it concatenates. So "5" + 3 is "53", while "5" - 3 is 2 because - only does math and converts the string to a number.

Comparison uses <, >, <=, >= and two kinds of equality:

  • === and !== (strict equality): true only if both type and value match. No conversion.
  • == and != (loose equality): convert operands first using rules that produce results like 0 == "" being true.

Always use ===. The one idiom some teams allow is x == null, which is true for both null and undefined.

NaN is not equal to anything, including itself; test it with Number.isNaN(x). Object.is(a, b) is like === but treats NaN as equal to itself and distinguishes 0 from -0.

The logical operators &&, || and ! short-circuit and return one of their operands, not necessarily a boolean:

  • a || b returns a if it is truthy, otherwise b.
  • a && b returns a if it is falsy, otherwise b.

That's why name || "Anonymous" works as a default. !!x converts any value to a boolean.

Example

console.log(7 % 3, 2 ** 10);    // 1 1024
console.log("5" + 3);           // "53"  (string concatenation)
console.log("5" - 3);           // 2     (numeric)

console.log(0 == "");           // true  (loose: avoid)
console.log(0 === "");          // false (strict)
console.log(null == undefined); // true
console.log(NaN === NaN);       // false
console.log(Number.isNaN(NaN)); // true

const input = "";
console.log(input || "default"); // "default"
console.log("a" && "b");          // "b"
console.log(!!"text");            // true

Remember

  • Use ===/!==; loose == converts types in surprising ways
  • + concatenates if either side is a string; other math operators convert to numbers
  • || and && return one of their operands, which makes them handy for defaults

Watch out for

  • Comparing with === NaN, which is always false — use Number.isNaN.

Check yourself

  1. What does "5" + 3 evaluate to?
  2. What does 0 || "fallback" return?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Equality_comparisons_and_sameness