JavaScript Booleans

A Boolean object in JavaScript has two values true and false. Let us see how to create a Boolean and Boolean object. We will also see the Boolean properties and methods with live running examples.

Create a Boolean and Boolean object

Let us see how to create a Boolean:

let b = true;

We can create a Boolean object using the new keyword:

let b = new Boolean(true);

JavaScript Boolean Properties

We have a constructor property in the Boolean object. Let us understand the property with an example.

boolean.constructor

Using the constructor property, a reference to the Boolean function is returned. This function created the object. Let us see an example:

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Boolean</h1>

<p id="test"></p>

<script>
var b = new Boolean( );

document.getElementById("test").innerHTML = b.constructor
</script>

</body>
</html>

Output

JavaScript boolean constuctor

JavaScript Boolean Methods

We have built-in methods for the Boolean object. Let us understand some of the methods with examples:

  • toString()
  • valueOf()

JavaScript toString() method

Use the toString() method to return the string representation based on the value of the object. Let us see an example:

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Boolean</h1>

<p id="test"></p>

<script>
// Boolean object
var b = new Boolean(true); 

// Return the string representation
document.getElementById("test").innerHTML = b.toString()
</script>

</body>
</html>

Output

JavaScript boolean toString() method

JavaScript valueOf() method

Use the valueOf() method in JavaScript to return the Boolean object. Let us see an example:

<!DOCTYPE html>
<html>
<body>

<h1>JavaScript Boolean</h1>

<p id="test"></p>

<script>
// Boolean object
var b = new Boolean(false); 

// Return the value of the Boolean object
document.getElementById("test").innerHTML = b.valueOf()
</script>

</body>
</html>

Output

JavaScript boolean valueOf() method

JavaScript Strings
JavaScript Math
Studyopedia Editorial Staff
[email protected]

We work to create programming tutorials for all.

No Comments

Post A Comment