Skip to content Skip to sidebar Skip to footer

Can't Understand The Conditional Execution Flow

A simple js snippet. Why does it always alert 'result is empty' As per my understanding, if block should get executed since result!='' is true and alert 'result is not empty'.

Solution 1:

It's because != does implicit type conversion. If you used the strict version, !==, it would do what you expect. But the loose version, !=, will convert both of those operands to numbers, and both "" and false convert to 0, so "" != false is false, because it ends up (through a series of convolutions) being 0 != 0.

This is laid out in detail in Abstract Equality Comparison algorithm in the specification:

  1. ReturnIfAbrupt(x).
  2. ReturnIfAbrupt(y).
  3. If Type(x) is the same as Type(y), then Return the result of performing Strict Equality Comparison x === y.
  4. If x is null and y is undefined, return true.
  5. If x is undefined and y is null, return true.
  6. If Type(x) is Number and Type(y) is String, return the result of the comparison x == ToNumber(y).
  7. If Type(x) is String and Type(y) is Number, return the result of the comparison ToNumber(x) == y.
  8. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
  9. If Type(y) is Boolean, return the result of the comparison x == ToNumber(y).
  10. If Type(x) is either String, Number, or Symbol and Type(y) is Object, then return the result of the comparison x == ToPrimitive(y).
  11. If Type(x) is Object and Type(y) is either String, Number, or Symbol, then return the result of the comparison ToPrimitive(x) == y.
  12. Return false.

As we can see from the above, if we start out with false and "", then:

  • We follow Step 8, convert false to 0, and start again with 0 != ""
  • We follow Step 6, convert "" to 0, and start again with 0 != 0
  • We follow Step 3 and get the result false (because we're doing !=, whereas the algorithm is defined in terms of ==).

Solution 2:

In javascript two falsy things can be equal, as in this case, where result != "" yields false.

You need to use an strict comparison, i.e. !== to make the comparison. result !== "" yields true.

Solution 3:

Javascript checks for truthy values.

false != ""

is false

false !== ""

is true so you can try it.

Post a Comment for "Can't Understand The Conditional Execution Flow"