Misunderstanding on parsing Boolean

Learn about how to parse boolean in Javascript.


Creating a boolean value using Boolean constructor

var b = new Boolean();

b is an object which have the value false in it. But the problem here is most of the beginner think as we can use directly in ifΒ , but it results to misunderstanding

if(b) {
   console.log("b is an object so it comes inside if");
}

b is no the boolean valueΒ , it is a boolean objectΒ . So we can’t use it directly to check the condition (Do not use a Boolean object in place of a Boolean primitive.). either we can use.

var booleanValue = b.valueOf()

The valueOf method of Boolean returns the primitive value of a Boolean object

Bonus 🀩

var b = Boolean('false');  evaluates to true
We can use 
var b = JSON.parse('false'); evaluates to false

Bonus Again 🀩🀩

Boolean value that are evaluates to false (source from mdn)

var noParam = new Boolean();
var zero = new Boolean(0);
var Null = new Boolean(null);
var EmptyString = new Boolean('');
var falseVal = new Boolean(false); 

Boolean value that are evaluates to true(source from mdn)

var trueVal = new Boolean(true);
var trueString = new Boolean('true');
var falseString = new Boolean('false');
var str = new Boolean('Javascript Jeep πŸš™ πŸš— ');
var ArrayVal = new Boolean([]);
var obj = new Boolean({});

If you find this helpful surprise 🎁 me here.

Share if you feel happy.

Follow Javascript JeepπŸš™ if you feel worthy.

Leave a comment

Design a site like this with WordPress.com
Get started