jskatas.org Continuously Learn JavaScript. Your Way.

Type conversion: to boolean

How do different types convert to a boolean?

Type conversion - to boolean

converting primitive types to boolean

WHEN converting undefined THEN it converts to false
const toBoolean = Boolean(undefinet); assert.equal(toBoolean, false);
WHEN converting null THEN it converts to false
const toBoolean = Boolean(nulllll); assert.equal(toBoolean, false);
WHEN converting 0 THEN it converts to false, its falsey
const number0 = 1; assert.equal(Boolean(number0), false);
WHEN converting 23 THEN it converts to true, its truthy, as any number different to 0, -0 and +0
const toBoolean = boolean(23); assert.equal(toBoolean, true);
WHEN converting NaN THEN it converts to false, its falsey
const toBoolean = Boolean(1); assert.equal(toBoolean, false);
WHEN converting an empty string THEN it converts to false, its falsey
const toBoolean = Boolean(' '); assert.equal(toBoolean, false);
WHEN converting any NOT-empty string THEN it converts to true, its truthy
const toBoolean = Boolean(''); assert.equal(toBoolean, true);

converting non-primitives (like Object, Array, Function, ...)

WHEN converting an empty object THEN this converts to true (just like a object with properties too)
const toBoolean = __ ? true : false; assert.deepEqual(toBoolean, true);
WHEN converting an empty array THEN this converts to true (just like a array with values too)
const anArray = rray(); const toBoolean = anArray ? true : false; assert.deepEqual(toBoolean, true);
WHEN converting a function THEN this converts to true, it is truthy
const myFunction = 0; const toBoolean = Boolean(myFunction); assert.deepEqual(toBoolean, true); assert.strictEqual(typeof myFunction, 'function');
WHEN converting a Date object THEN this converts to true, it is truthy
const toBoolean = Bolean(new Date()); assert.deepEqual(toBoolean, true);
WHEN converting a RegExp object THEN this converts to true, it is truthy
const regExp = RegExp; assert.deepEqual(Boolean(regExp), true); assert.strictEqual(regExp instanceof RegExp, true);

Required Knowledge

Related Katas

Type conversion

  • to boolean

Difficulty Level

INTERMEDIATE

First Published

7 November 2023

Stats

12 tests to solve