Booleans in JavaScript

JavaScript Booleans: In this tutorial, we will learn about the Boolean data types in JavaScript with the help of examples. By Siddhant Verma Last updated : July 29, 2023

JavaScript Boolean

Boolean is a data type that stores only two values: true and false.

Alternately, true is represented by 1 and false by 0. However, anything other than false is considered true. This means that if you define your false to be 0 everything other than 0 will be considered true. More accurately, a variable or an object having some value is treated as true and 0, NaN, empty string, undefined, null is treated as false.

Even without explicitly using boolean, we use it unknowingly various times since most conditional statements work on executing a certain piece of code if their condition returns true. If you have ever used while loop, you are indirectly using the booleans.

Boolean variables declarations

We declare a boolean as we declare normal variables.

Boolean in JavaScript Example 1

Note: how b and bool both store the value true? But, bool is a boolean and b is not. We need not use ' ' a or " " while defining boolean values otherwise will be considered a string.

Checking Boolean values

We can use the inbuilt Boolean() function to check if something has a true value or a false value. Anything passed as a parameter to the Boolean() function is evaluated for true and false.

Boolean in JavaScript Example 2

You can also evaluate expressions using this method.

Boolean in JavaScript Example 3

Boolean variables declarations with new keyword

You can also use JavaScript's boolean object for wrapping boolean values in an object declared using the "new" keyword.

Boolean in JavaScript Example 4

This boolean object has a constructor property, a toString() method and a valueOf() method. Let's have a brief overview of what they do and how to use them.

    var b=new Boolean("");
    console.log(b);
    console.log(b.constructor);

It returns something ƒ Boolean() { [native code] }. This is nothing but the constructor function for this object.

The toString() method simply returns a string with 'true' or 'false' depending on the type of boolean passed to the object and valueOf() method returns a boolean indicating true or false depending on the value that boolean stores.

Boolean in JavaScript Example 5

JavaScript Tutorial »




Comments and Discussions!

Load comments ↻






Copyright © 2024 www.includehelp.com. All rights reserved.