Reputation: 185
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
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
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
Reputation: 31606
In Javascript the following values are treated as false
for conditionals:
false
null
undefined
''
0
NaN
Everything else is treated as true
.
'false'
is none of the above, so it's true
.
Upvotes: 15
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
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 == '' // true0 == '0' // true
false == 'false' // false
false == '0' // truefalse == undefined // false
false == null // falsenull == 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
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