Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript if condition on boolean

Tags:

javascript

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");
}
like image 321
user1052591 Avatar asked Dec 01 '11 22:12

user1052591


People also ask

How do you write a boolean condition in an if statement in JavaScript?

An if statement checks a boolean value and only executes a block of code if that value is true . To write an if statement, write the keyword if , then inside parentheses () insert a boolean value, and then in curly brackets {} write the code that should only execute when that value is true .

How check boolean value in if conditions in typescript?

Use the typeof operator to check if a value is of boolean type, e.g. if (typeof variable === 'boolean') . The typeof operator returns a string that indicates the type of a value. If the value is a boolean, the string "boolean" is returned.

How do you check if a variable is a boolean in JavaScript?

Using the typeof Operator The typeof operator is used to check the variable type in JavaScript. It returns the type of variable. We will compare the returned value with the “boolean” string, and if it matches, we can say that the variable type is Boolean.


1 Answers

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.

like image 106
Davy8 Avatar answered Sep 28 '22 09:09

Davy8