JavaScript Boolean


A JavaScript Boolean represents one of two values: true or false.

Syntax

var val = new Boolean(value);

Boolean Values

Very often, in programming, you will need a data type that can only have one of two values, like

  • YES / NO
  • ON / OFF
  • TRUE / FALSE

For this, JavaScript has a Boolean data type. It can only take the values true or false.


Boolean() Function

The Boolean() function to find out if an expression (or a variable) is true:

Example

<span id="view"></span>

<script type="text/javascript">
function check() 
 {
  var a = Boolean(5 > 2);
    document.getElementById("view").innerHTML = a;
}
</script>

<input type="button" onclick="check()" value="Check" />
Output


or

<span id="view"></span>

<script type="text/javascript">
function check() 
 {
    document.getElementById("view").innerHTML = Boolean(5 > 2);
}
</script>

<input type="button" onclick="check()" value="Check" />
Output



Everything With a Real Value is True

<span id="view"><⁄span><br/>
<span id="view2"><⁄span><br/>
<span id="view3"><⁄span><br/>
<span id="view4"><⁄span><br/>
<span id="view5"><⁄span><br/>
<span id="view6"><⁄span>

<script type="text/javascript">
function check()
 {
  var a = Boolean(10);
  var b = Boolean(2.1498);
  var c = Boolean(-49);
  var d = Boolean("Hi");
  var e = Boolean('false');
  var f = Boolean(3 + 12.76);
  
  document.getElementById("view").innerHTML ="10 is " + a;
  document.getElementById("view2").innerHTML ="2.1498 is " + b;
  document.getElementById("view3").innerHTML ="-49 is " + c;
  document.getElementById("view4").innerHTML ="Any (not empty) string is " + d;
  document.getElementById("view5").innerHTML ="Even the string 'false' is " + e;
  document.getElementById("view6").innerHTML ="Any expression (except zero) is " + f;
}
</script>

<input type="button" onclick="check()" value="Check" />
Output





 

Everything Without a Real Value is False

The Boolean value of 0 (zero) is false.

var x = 0;
Boolean(x);       // returns false

The Boolean value of -0 (minus zero) is false.

var x = -0;
Boolean(x);       // returns false

The Boolean value of "" (empty string) is false.

var x = "";
Boolean(x);       // returns false

The Boolean value of undefined is false.

var x;
Boolean(x);       // returns false

The Boolean value of null is false.

var x = null;
Boolean(x);       // returns false

The Boolean value of false is (you guessed it) false.

var x = false;
Boolean(x);       // returns false

The Boolean value of NaN is false.

var x = 10 / "H";
Boolean(x);       // returns false

Share this article on