JavaScript : Boolean Function Coercion

JavaScript : Boolean Function Coercion

The programmer can use the Boolean() function to convert any type to a boolean. In this post, I discuss the multiple use cases for boolean conversion.

Boolean() function Coercion

The boolean() function converts a given value to a boolean. The value can be a primitive, an object or an expression as well.

The boolean function returns, false for the given input values - undefined, null, 0, -0, 0n, "" and NaN. For other primitive values, the function returns true.

The boolean() function internally uses the double-not operator.

// Boolean co-ercion
console.log(Boolean(undefined)); // false
console.log(Boolean(0), Boolean(-0)); // false false
console.log(Boolean(NaN)); // false
console.log(Boolean([]));  // true
console.log(Boolean(""));  // false
console.log(Boolean([]));  // true
console.log(Boolean(null));  // false
console.log(Boolean(10n));  // true
console.log(Boolean(0n));  // false
console.log(Boolean({}));  // true
console.log(Boolean("0"));  // true