user1052591
user1052591

Reputation: 185

Javascript if condition on boolean

Can you explain why the if condition doesn't work without the eval function:

var myBoolean= document.getElementById("someBoolean").value;  //This is a 'false'

if(myBoolean)
{ 
  alert(Your boolean is True);  //This condition always getting executed even though myBoolean is false;
}

if(eval(myBoolean))
{
 alert("You will never see this alert bcoz boolean is false");
}

Upvotes: 13

Views: 32608

Answers (7)

duckisland
duckisland

Reputation: 1

A string IS a boolean truth value according to ECMA

var a = ""<br/>
a&&false //-> false<br/>
a||false //-> "" (truthy)<br/>

Upvotes: -1

Boundless
Boundless

Reputation: 2464

Try:

var myBoolean= document.getElementById("someBoolean").value;  //This is a 'false'

if(myBoolean != "false")
{ 
  alert(Your boolean is True);  //This condition always getting executed even though myBoolean is false;
}

Like others have said, a string isn't a boolean value, so using it as though it was will give you a logical error.

Upvotes: 0

David Ly
David Ly

Reputation: 31606

In Javascript the following values are treated as false for conditionals:

  • false
  • null
  • undefined
  • The empty string ''
  • The number 0
  • The number NaN

Everything else is treated as true.

'false' is none of the above, so it's true.

Upvotes: 15

gen_Eric
gen_Eric

Reputation: 227310

This is because it's not actually a boolean, it's a the string 'false'. When you convert a string to a boolean, '' is false and anything else is true.

You check if it's equal to the string 'false' (or 'true') or not.

var myBoolean = 'false'; // (string)
myBoolean = myBoolean !== 'false'; //false (boolean)

Upvotes: 2

AlexC
AlexC

Reputation: 10766

'false' == true, crazily enough because of JavaScript's implicit type coercion. Check out these other examples from Crockford's The Elements of JavaScript Style.

'' == '0' // false
0 == '' // true

0 == '0' // true

false == 'false' // false
false == '0' // true

false == undefined // false
false == null // false

null == undefined // true

' \t\r\n ' == 0 // true

You could solve this particular problem by changing your code to something like

var myBoolean = document.getElementById("someBoolean").value === "true"

Also, it is almost always better to use !! and === rather than ! and ==

Upvotes: 1

Tim Wickstrom
Tim Wickstrom

Reputation: 5701

document.getElementById("someBoolean") does not return a boolean true/false it returns an element or undefined / null

you could reverse your logic and get the expected result:

    if(!myBoolean)
    { 
      alert('This element does not exist');
    }

    if(!eval(myBoolean))
    {
     alert("Do not know why you would ever want to do this");
// you could do typeof() 
    }

Upvotes: 0

jamesfzhang
jamesfzhang

Reputation: 4501

The string 'false' evaluates to the boolean true

Upvotes: 5

Related Questions