Boolean in Javascript-tutorial
In JavaScript, the boolean is a primitive data type used to represent logical values
How to Create Boolean Objects
- true
- false
How to Create Boolean Objects
While you can use primitive boolean values directly (true or false), JavaScript also allows you to create Boolean objects using the Boolean constructor.
var b = new Boolean(true);
By default, the value is false if no argument is passed.
Example:
<!DOCTYPE html><html>
<body> <script> document.write(10 < 20); // true document.write("<br>"); document.write(10 < 5); // false </script></body>
</html>
Output
.webp)
boolean Properties
constructor
Returns a reference to the Boolean function that created the object's prototype.
var b = new Boolean(true);console.log(b.constructor); // Output: ƒ Boolean() { [native code] }
prototype
Allows you to add new properties or methods to all Boolean objects.
Boolean Methods
JavaScript's Boolean object inherits some useful methods from the generic object prototype, like
- toString() - Converts boolean value to string ("true" or "false").
- valueOf() - Returns the primitive value (true or false).
Example:
var b = new Boolean(false);
console.log(b.toString()); // "false"console.log(b.valueOf()); // false
Key Point
- Booleans represent only two values: true or false.
- Boolean objects (new Boolean()) are rarely needed; primitive values are usually sufficient.
- Use booleans in conditions to control logic in your program.