More

Lecture Notes

Course: Web Development Masterclass

Lecture: JavaScript Booleans

The `boolean()` function can be used to find out if an expression or variable is true.

As a general rule everything with a "real" value is true. Anything without a "real" value is false.

Let's take a look at an example.

``` <!DOCTYPE html> <html> <body> <p id="demo"></p> <script> var b1 = Boolean(80); var b2 = Boolean(2.86); var b3 = Boolean(-10); var b4 = Boolean("Hi"); var b5 = Boolean('false'); var b6 = Boolean(1 + 8 + 10.14); var b7 = Boolean(0); document.getElementById("demo").innerHTML = "80 is " + b1 + "<br>" + "2.86 is " + b2 + "<br>" + "-10 is " + b3 + "<br>" + "Any (not empty) string is " + b4 + "<br>" + "The string 'false' is " + b5 + "<br>" + "Any expression (except zero) is " + b6 + "<br>" + "Zero is " + b7; </script> </body> </html> ```

In this script we have a 6 variables declared. b1 to b6.

Each variable uses the `boolean()` function to test whether a specified value is true.

Using the `getElementByID` method, we can output the data.

Let's take a look at this page in our web browser to see the results.

We can see that all the numbers including, 80, 2.86, -10 are true. The same goes for variable b6 which contained the equation.

The strings including variable b4 and b5 are also true.

The last variable, variable b7 is false.