Learn javascript Boolean Object Basics
- Admin
- Dec 31, 2023
- Javascript
Boolean objects vs primitive types
These are objects which represent true or false boolean primitive values only. Do not confuse true and false values. these are boolean primitive types. Both are serving different purposes.
Syntax
new Boolean(optional value)
optional value is optional which contains the default value if the first parameter to the Boolean object is empty,0, NaN, Undefined, null, false, Boolean object has an initial value of false. If the Boolean object has parameter values like ‘false’, any object, Boolean holds true value.
Different ways to create a boolean falsy value
the below objects returns false values
var emptyBoolean = new Boolean();
var zeroBoolean = new Boolean(0);
var nullBoolean = new Boolean(null);
var emptyString = new Boolean("");
var undefinedBoolean = new Boolean(undefined);
var nanBoolean = new Boolean(NaN);
var falseBoolean = new Boolean(false);
Different ways to create Boolean object truthy values
The below objects returns true values
var falseStringBoolean = new Boolean("false");
var trueBoolean = new Boolean(true);
var zeroBoolean = new Boolean("stringa");
var zeroBoolean = new Boolean({});
var zeroBoolean = new Boolean(0);
Boolean Object Methods Boolean object inherit from Boolean.prototype() which inherit from Object.prototype() global object. all global methods will be available Boolean toString method which converts to String format
true.toString(); // returns true
false.toString(); // returns false
valueOf() method this method returns primitive value of Boolean object
boolObject = new Boolean();
console.log(booleObject.valueOf()); // returns false
Convert string boolean to Boolean in javascript
Many ways we can convert to boolean, one way is to use Json.parse() method
JSON.parse('true') - returns boolean true
JSON.parse('false') - returns boolean false
Boolean(1).toString(); // true
Boolean(0).toString(); // false
var boolVal = Boolean("false");
var myBoolean = Boolean.parse(boolString);
Difference between the Boolean object and boolean primitive type
The boolean data type has only valued true or false. Boolean Object is like any other object new Boolean(true), new Boolean(false)
var booleanPrimitve = true;
var otherBooleanPrimitve = true;
var booleanObj = new Boolean(true);
var otherBooleanObj = new Boolean(true);
console.log(booleanPrimitve == otherBooleanPrimitve); // returns true, as both values are equal
console.log(booleanObj == otherBooleanObj); // returns false - both are different objects
How to convert Boolean to Number in javascript
Number object has a constructor which takes boolean values, we can easily convert boolean to Number
console.log(Number(true)); // returns 1
console.log(Number(false)); // returns 0
console.log(Number("true")); // returns NaN as we are passing strings
console.log(Number("false")); // returns NaN as we are passing strings