Hao Zonggang Hao Zonggang - 4 months ago 14
Javascript Question

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

Answer

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

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

While doing

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

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

One difference though is using the anonymous function lets you do other things before ultimately processing/returning val as a boolean, eg manipulate val before passing it to Boolean

Comments