user1052591 user1052591 - 2 years ago 105
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'

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

alert("You will never see this alert bcoz boolean is false");

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download