Equality, Truthy and Falsy

== converts before comparing, === does not. And every value counts as true or false in an if: see which ones are falsy.

JavaScript · beginner · 6 min · 16 steps · free

What you'll learn

Equality.js

const a = 0;
const b = '0';
console.log(a == b);
console.log(a === b);

const values = [0, '', 'hello', null, []];
for (const v of values) {
  if (v) {
    console.log(v, 'is truthy');
  } else {
    console.log(v, 'is falsy');
  }
}

Step by step

  1. a is created with the value 0.
  2. b is created with the value "0".
  3. 0 == "0" is true: == converts the string to a number before comparing.
  4. 0 === "0" is false: a number and a string are never strictly equal.
  5. values is created and points to a new Array: [0, "", "hello", null, an Array].
  6. A loop over v begins.
  7. An if does not need true or false: 0 counts as false. Values that count as false are called falsy.
  8. It prints 0 is falsy.
  9. v is "", which is falsy, so the if-block is skipped.
  10. It prints is falsy.
  11. v is "hello", which is truthy, so the if-block runs.
  12. It prints hello is truthy.
  13. v is null, which is falsy, so the if-block is skipped.
  14. It prints null is falsy.
  15. An empty array is truthy: every object is, even an empty one.
  16. It prints [] is truthy.

Common mistakes

Best practices

Key takeaways

Check yourself

null === undefined?

Answer: false. Different types.

if ("0") runs?

Answer: Yes. "0" is a non-empty string, so it is truthy.

·

More in The Basics