JavaScript Booleans - Learn Booleans in JavaScript



JavaScript Booleans

  • A JavaScript Boolean contains two values: true or false.

Boolean Values

In programming, you will frequently require a data type that can only hold one of two values, such as

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

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

The Boolean() Function

  • You can use the Boolean() function to find out if an expression (or a variable) is true.
js-boolean-function

Sample Code

<html>
<body>

<h2>JavaScript Booleans</h2>
<p>The value of Boolean(20 > 10):</p>

<p id="bool"></p>

<script>
document.getElementById("bool").innerHTML = Boolean(20 > 10);
</script>

</body>
</html>

Output

JavaScript Booleans
The value of Boolean(20 > 10):
True

Conditions and Comparisons

Operator Description Example
== equal to if (day == "Monday")
> greater than if (salary > 9000)
< less than if (age < 18)

Everything With a "Value" is True

js-boolean-value-is-true

Sample Code

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Booleans</h2>
<p id="demo"></p>

<script>
document.getElementById("demo").innerHTML =
"300 is " + Boolean(300) + "<br>" +
"4.14 is " + Boolean(4.14) + "<br>" +
"-65 is " + Boolean(-65) + "<br>" +
"Any (not empty) string is " + Boolean("Hello") + "<br>" +
"Even the string 'false' is " + Boolean('false') + "<br>" +
"Any expression (except zero) is " + Boolean(5 + 5 + 4.14);
</script>

</body>
</html>

Output

JavaScript Booleans
300 is true
4.14 is true
-65 is true
Any (not empty) string is true
Even the string 'false' is true
Any expression (except zero) is true

Everything Without a "Value" is False

js-boolean-value-false

Sample Code

<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Booleans</h2>
<p>Display the Boolean value of 0:</p>

<p id="demo"></p>

<script>
let x = 0;
document.getElementById("demo").innerHTML = Boolean(x);
</script>

</body>
</html>

Output

JavaScript Booleans
Display the Boolean value of 0:
false

Related Searches to JavaScript Booleans - Learn Booleans in JavaScript