Thursday, July 19, 2018

Learn javascript Boolean Object Basics

Boolean objects vs primitive types

are objects which represent true or false boolean primitive values only. Do not confuse with true and false values. these are boolean primitive types.Both are serving for different purpose

Syntax

new Boolean(optional value)
optional value is optional which contains 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

Boolean object creation for false

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);

Boolean object creation for true

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

boolean data type has only values true or false. Boolean Object is like any other objects 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

Boolean to Number conversion 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

Related article


EmoticonEmoticon