Hao Zonggang Hao Zonggang - 1 year ago 82
Javascript Question

Don't really understand Boolean() function

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

return Boolean(val)


Also,are these two are functionally equal?

var x = new Boolean(expression);

var x = Boolean(expression);

Answer Source

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.


Boolean here is used as a callback method

While doing

  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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download