Home »
JavaScript
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.
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.
You can also evaluate expressions using this method.
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.
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.
JavaScript Tutorial »