JS: Boolean Constructor

By Xah Lee. Date: . Last updated: .
  1. Boolean (arg) → Convert arg to true or false, return it.
  2. new Boolean (arg) → Return a Boolean object that represent true/false of arg.

When called as a function, it's used to convert a value to a boolean value, in the same way a “if” statement determines true/false.

// Boolean called as a function, returns true/false primitive value
console.log ( (typeof Boolean(3)) === "boolean" ); // true

// Boolean called as a constructor, returns boolean object
console.log ( (typeof (new Boolean(3))) === "object" ); // true

Converting values to boolean.

// the following eval to false

console.log( Boolean(0) ); // false
console.log( Boolean(0.0) ); // false
console.log( Boolean(0.) ); // false
console.log( Boolean(.0) ); // false

console.log( Boolean("") ); // false

console.log( Boolean(null) ); // false
console.log( Boolean(undefined) ); // false
console.log( Boolean(NaN) );    // false

// anything else is true

console.log( Boolean(1) ); // true
console.log( Boolean(-1) ); // true
console.log( Boolean(Infinity) ); // true
console.log( Boolean({}) ); // true
console.log( Boolean([]) ); // true
console.log( Boolean(function () {}) ); // true

Creating boolean object.

let xx = new Boolean(0);
console.log( xx.valueOf() === false ); // true

Tip: the only practical use of Boolean() is to force a value into true or false.

new Boolean(…) is not very useful.

Reference

ECMAScript® 2016 Language Specification#sec-boolean-constructor

Boolean Topic

  1. JS: true, false
  2. JS: Boolean Object
  3. JS: Boolean.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth