Killy
Killy

Reputation: 330

javascript true and false

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

Upvotes: 1

Views: 614

Answers (3)

Luka Krajnc
Luka Krajnc

Reputation: 915

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
}

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172398

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

Upvotes: 1

Pointy
Pointy

Reputation: 413702

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.

Upvotes: 4

Related Questions