1

i already know the following behavior, but can someone tell me WHY this happens? Thanks.

if("hello"==true)alert("it's true!"); //-> does not fire the alert
if("hello"==false)alert("it's true!"); //-> does not fire the alert
if("hello")alert("it's true!"); //-> fires the alert
Killy
  • 300
  • 5
  • 13
  • 1
    The answers to all such questions can be found [in the spec.](http://www.ecma-international.org/ecma-262/5.1/#sec-11.9.3) – Pointy Sep 01 '14 at 13:51
  • possible duplicate of [Why does “true” == true show false in JavaScript?](http://stackoverflow.com/questions/11363659/why-does-true-true-show-false-in-javascript) – Qantas 94 Heavy Sep 01 '14 at 13:51

3 Answers3

4

In the first two, you're explicitly comparing a string to the boolean constants, and the string is obviously not equal to either. In the third line, you're testing the "truthiness" of the string, and any non-empty string evaluates to true in that context.

In a comparison between a string and a boolean, the Abstract Equality Comparison Algorithm dictates that the comparison should be carried out as a numeric comparison. Thus true is converted to 1 and false to 0; "hello" will be NaN. NaN is never == to anything.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • 1
    +1 for the Abstract Equality Comparison Algorithm part. – Rahul Tripathi Sep 01 '14 at 13:51
  • But why a non-empty string and other stuff like that (i.e. numbers greater than zero) equals to true? Is there some specification about that? – Killy Sep 01 '14 at 13:51
  • [Yes there is a specification for that.](http://www.ecma-international.org/ecma-262/5.1/) In particular, [section 9.2 describes how values are interpreted as boolean.](http://www.ecma-international.org/ecma-262/5.1/#sec-9.2) – Pointy Sep 01 '14 at 13:52
  • Thank you Pointy, the "IF" specification http://www.ecma-international.org/ecma-262/5.1/#sec-12.5 plus the "ToBoolean" specification http://www.ecma-international.org/ecma-262/5.1/#sec-9.2 are the key. – Killy Sep 01 '14 at 14:18
1

true and false are boolean values and you are trying to compare boolean with string value hence you are facing the issue since the condition is not satisfied.

In the third case you are not comparing you are simply making a check of true

Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
1

You can't compare string ("HELLO") with boolean (true). They are 2 different types. The last alert triggers because you aren't comparing it to anything. It will only returned if you will test empty string

var foo = "Hello world!"; 
if(foo){ 
  //if foo is not empty 
}else{ 
  //if foo is empty
}
Luka Krajnc
  • 915
  • 1
  • 7
  • 21
  • i knew that the "===" operator checks for types and the "==" does not... that's why i was expecting that a [not-empty-string] (that is interpreted as true) compared with [true] returns [true] – Killy Sep 01 '14 at 14:01