Skip to content

JavaScript Boolean, Boolean() | Basics

  • by

JavaScript has a Boolean data type and a Boolean variable value can be TRUE or FALSE. The boolean function returns the boolean value of a variable.

  • The boolean primitive type has two values of true and false.
  • The Boolean object is an object wrapper for a boolean value.
  • Use the Boolean() function to find out if an expression (or a variable) is true:

JavaScript boolean examples

Simple example code boolean primitive type. The following example declares two variables that hold boolean values of false and true:

<!DOCTYPE html>
<html>
<body>
  <script>

    let isPending = false;
    let isDone = true;

    console.log("isPending", isPending, typeof(isPending))
    console.log("isDone", isDone, typeof(isDone))

  </script>
</body>
</html>

Output:

JavaScript Boolean

Boolean object

Use the Boolean() function to convert a string into a boolean value. Because the string is not empty, it returns true.

let a = Boolean('Hi');
console.log(a); // true
console.log(typeof(a)); // boolean

The Boolean is also a wrapper object of the boolean primitive type. It means that when you pass either true or false to the Boolean constructor, it’ll create a Boolean object.

let b = new Boolean(false);
OperatorbooleanBoolean
 typeofbooleanobject
 instanceof Booleanfalsetrue

Here’s a simple example of how booleans are used in JavaScript:

var isRaining = true;

if (isRaining) {
    console.log("Take an umbrella!");
} else {
    console.log("Enjoy the sunshine!");
}

In this example, the variable isRaining is assigned the value true, so the code inside the if block will execute, resulting in the message “Take an umbrella!” being logged to the console.

You can also use boolean operators like && (AND), || (OR), and ! (NOT) to perform logical operations with booleans. For example:

var hasMoney = true;
var hasCreditCard = false;

if (hasMoney || hasCreditCard) {
    console.log("You can buy something!");
} else {
    console.log("You cannot buy anything!");
}

In this example, the code inside the if block will execute because at least one of the conditions (hasMoney or hasCreditCard) evaluates to true. Therefore, the message “You can buy something!” will be logged to the console.

Comment if you have any doubts or suggestions on this JS boolean topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading