user1052591 user1052591 - 6 months ago 19
Javascript Question

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");
}

Answer

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.