/

HTML / CSS / JavaScript Tutorial

JavaScript Global method: Boolean()

[this page | pdf | back links]

The JavaScript Global Boolean() method converts an object to a Boolean representing the value of the object. If the parameter value is omitted or is 0, -0, false, NaN, undefined, an empty string or the document.all DOM object then the method evaluates to false. All other parameter values (including the string “false”!) evaluate to true.

 

It has the following syntax with the following parameters:

 

Boolean(x)

 

Parameter

Required / Optional

Description

x

Optional

Input parameter. If missing, then returns false.

 

Note: it is easy to confuse the primitive Boolean values true and false with the values of the Boolean object. For example, any object whose value is not undefined or null evaluates to true when passed to a conditional statement. So, the following statements will result in the code being evaluated:

 

     var x = new Boolean(false);

     if (x) { code }

 

whereas it will not be executed with the following statements:

 

     var x = false;

     if (x) { code }

 

The output of the global Boolean method can also be quite confusing at it involves a type coercion that does not always behave intuitively.

 

EXAMPLE:


HTML USED IN THIS EXAMPLE:
<!DOCTYPE html>
<html> <!-- Copyright (c) Nematrian Limited 2018 -->
<head>
<style>
table,th,tr,td {border: 1px solid black; border-collapse :collapse;}
</style>
</head>
<body>
<table>
<tr>
<th>Example</th>
<th>Resulting value of <code>x</code></th>
</tr>
<tr>
<td><code id="Example"></code></td>
<td><code id="Result"></code></td>
</tr>
</table>

<script>
document.getElementById("Example").innerHTML =
  'var x = Boolean("False");';
document.getElementById("Result").innerHTML =
  Boolean("False");
</script>

</body>
</html>

FUNCTION THAT MAY ASSIST IN TESTING WHETHER FEATURE IS SUPPORTED:
function isSupportedJavaScriptMethodGlobalBoolean() {
  return Boolean("Hello");
}


NAVIGATION LINKS
Contents | Prev | Next | JavaScript DOM (and BOM)


Desktop view | Switch to Mobile