Coercive Conditional Comparison

Yes, that section name is quite a mouthful. But what are we talking about? We’re talking about conditional expressions needing to perform coercion-oriented comparisons to make their decisions.

if and ? :-ternary statements, as well as the test clauses in while and for loops, all perform an implicit value comparison. But what sort? Is it “strict” or “coercive”? Both, actually.

Consider:

  1. var x = 1;
  2. if (x) {
  3. // will run!
  4. }
  5. while (x) {
  6. // will run, once!
  7. x = false;
  8. }

You might think of these (x) conditional expressions like this:

  1. var x = 1;
  2. if (x == true) {
  3. // will run!
  4. }
  5. while (x == true) {
  6. // will run, once!
  7. x = false;
  8. }

In this specific case — the value of x being 1 — that mental model works, but it’s not accurate more broadly. Consider:

  1. var x = "hello";
  2. if (x) {
  3. // will run!
  4. }
  5. if (x == true) {
  6. // won't run :(
  7. }

Oops. So what is the if statement actually doing? This is the more accurate mental model:

  1. var x = "hello";
  2. if (Boolean(x) == true) {
  3. // will run
  4. }
  5. // which is the same as:
  6. if (Boolean(x) === true) {
  7. // will run
  8. }

Since the Boolean(..) function always returns a value of type boolean, the == vs === in this snippet is irrelevant; they’ll both do the same thing. But the important part is to see that before the comparison, a coercion occurs, from whatever type x currently is, to boolean.

You just can’t get away from coercions in JS comparisons. Buckle down and learn them.