Hao Zonggang
Hao Zonggang

Reputation: 73

Don't really understand Boolean() function

Is these two are functionally equal?If so,how(important)?

arr.filter(function(val){
  return Boolean(val)
});

arr.filter(Boolean);

Also,are these two are functionally equal?

var x = new Boolean(expression);

var x = Boolean(expression);

Upvotes: 0

Views: 33

Answers (2)

Patrick Evans
Patrick Evans

Reputation: 42736

The second one no, the one using new creates an instance of Boolean, while the other just returns the boolean equivalent of what was passed to it, eg turn a truthy/falsy value into an actual boolean true/false value.

console.log( "Is instance: ", (new Boolean(true)) instanceof Boolean );
console.log( "Is not instance: ", Boolean(true) instanceof Boolean );

console.log("truthy to bool: ", Boolean(-1) );
console.log("falsey to bool: ", Boolean(0) );
console.log("falsey to bool: ", Boolean("") );
console.log("truthy to bool: ", Boolean("test") );

They are also different in how you would use them in a conditional statement. For instance a primitive boolean value you can use alone in a conditional

if(true) // 
if(false) //

But if you try to test with a Boolean instance alone, the conditional will always be true as it is an object, and all objects are truthy, even empty objects

var d = new Boolean(false);
if(d){
   console.log("Gets called even though the Boolean instance holds a false value");
}

The first is equivalent, in that they result in the same thing, because in both cases a boolean value will be returned to the filter internals.

arr.filter(Boolean);

Boolean here is used as a callback method and takes the return value directly from Boolean's returned value.

While doing

arr.filter(function(val){
  return Boolean(val)
});

is using an anonymous function as the callback method and so the value is indirectly returned from Boolean. But in both cases a value is passed to Boolean and then returned so the result is the same.

Note though the below would not be the same:

arr.filter(function(val){
  return new Boolean(val);
});

As stated above, an instance of Boolean is an object, it will always be a truthy value. So in the above example all elements of the array would pass the test and therefore you would end up with same array that you were trying to filter.

The use of the anonymous function lets you do other things before ultimately processing/returning val as a boolean, eg manipulate val before passing it to Boolean

Upvotes: 4

Amit
Amit

Reputation: 46323

First snippet, yes these are functionally identical.

Second version, no these will result in different values. The first will result in a Boolean object instance with a truthy/falsey value and the second will result in a primitive truthy/falsey value.

Read more here.

Upvotes: 0

Related Questions