The Boolean object is one of the three wrapper objects of JavaScript. As a constructor, it is mainly used to generate Boolean-valued packaging object instances.

var b = new Boolean(true);

typeof b; // "object"
b.valueOf(); // true

The variable b in the above code is an instance of a Boolean object, its type is object, and its value is the Boolean value true.

Note that for the package object instance corresponding to false, the result of the Boolean operation is also true.

if (new Boolean(false)) {
} // true

if (new Boolean(false).valueOf()) {
} // no output

The first example of the above code gets true because the package object instance corresponding to false is an object, which is automatically converted into a boolean value true when performing logical operations (because all objects correspond to boolean values Both are true). The valueOf method of an instance returns the original value corresponding to the instance, which is false in this example.

Type conversion effect of Boolean function

In addition to being used as a constructor, the Boolean object can also be used alone to convert any value to a Boolean value. At this time, Boolean is a pure tool method.

Boolean(undefined); // false
Boolean(null); // false
Boolean(0); // false
Boolean(""); // false
Boolean(NaN); // false

Boolean(1); // true
Boolean("false"); // true
Boolean([]); // true
Boolean({}); // true
Boolean(function () {}); // true
Boolean(/foo/); // true

Several situations where true is obtained in the above code are all worth remembering carefully.

By the way, using the double negation operator (!) can also convert any value to the corresponding Boolean value.

!!undefined; // false
!!null; // false
!!0; // false
!!""; // false
!!NaN; // false

!!1; // true
!!"false"; // true
!![]; // true
!!{}; // true
!!function () {}; // true
!!/foo/; // true

Finally, for some special values, adding or not adding new in front of the Boolean object will get the exact opposite result, so you must be careful.

if (Boolean(false)) {
} // no output

if (new Boolean(false)) {
} // true

if (Boolean(null)) {
} // no output

if (new Boolean(null)) {
} // true