1

Possible Duplicate:
Why does (‘0’ ? ‘a’ : ‘b’) behave different than (‘0’ == true ? ‘a’ : ‘b’)

I'm currently learning Javascript and so far am pleased about the language.

This morning, when writing a test, I realized something I can't explain:

When evaluating boolean expressions, we have:

// a && b returns b in case a && b are evaluated to true: OK
'2' && '3' => '3'
'3' && '2' => '2'

// a && b returns a in case a is evaluated to false, b otherwise: OK
false && '' => false
'' && false => ''

// '' and '0' are evaluated to false in a boolean context: OK
'' == false => true
'0' == false => true

// Here is the "problem":
'' && '0' => '' // To be expected: both operands evaluate to false
'0' && '' => '' // What ?!!

So my question is simple: why does '0' && '' return '' ?

I would expect both operands to evaluate to false but it seems in that context '0' does not. Why is so ?

Community
  • 1
  • 1
ereOn
  • 53,676
  • 39
  • 161
  • 238
  • The MDN seems to offer a good explanation: https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Operators/Logical_Operators. `Boolean('0') == true` for some reason. – Blender Oct 17 '12 at 09:14
  • @AndreKR: That question indeed answers mine. Thanks for the link. Voted to close too. – ereOn Oct 17 '12 at 09:25
  • Even better answers at [JavaScript type conversion: (true && 1) vs (true | | 1)](http://stackoverflow.com/questions/8559920/javascript-type-conversion-true-1-vs-true-1) – Old Pro May 11 '13 at 18:58
  • @OldPro: No offense but, the question you quoted has little to do with the expressed problem actually. My question is about different behavior of the same operator `&&` depending on the operands while this other question is about the difference between the `&&` and `||` operators. – ereOn May 13 '13 at 08:42
  • @ereOn, sorry, I skimmed your question and saw you didn't understand why `'0' && '' => ''` and missed that you didn't understand that `'0'` is truthy. I see now your fundamental confusion was from the supremely confusing `==` operator that yields `'0' == false => true`. – Old Pro May 13 '13 at 09:05

1 Answers1

2

'' is a falsey value while '0' is not a falsey value.

(When trying '0' == false the == does a type conversions so it returns true. )

CD..
  • 72,281
  • 25
  • 154
  • 163
  • So why does a "non-falsey" value does evalutate to `false` when using `==` ? – ereOn Oct 17 '12 at 09:17
  • You know this now, but for the sake of future readers, `'0' == false` is `true` because both are converted to numbers for comparison by the `==` operator, so the comparison ends up being `0 == 0`. – Old Pro May 13 '13 at 09:53