Javascript built-in data structure - Boolean

This tutorial is a part of the Learn everything about Javascript in one course.

Boolean is a data structure to represent logical values. It only has two values: true and false. Boolean is usually an output of logical operator (we will learn more about these operators later) or Boolean() function.

Frequently used Boolean() checks:

Input Example Output
Number: none zero 0 Boolean(1) true
Number: zero 0 Boolean(0) false
Number: NaN Boolean(NaN) false
String: none-empty string Boolean('a') true
String: empty string Boolean('') false
null Boolean(null) false
undefined Boolean(undefined) false
empty array [] Boolean(![].length)
Boolean([]) wrong, do not use!
true
empty object {} Boolean(!Object.keys({}).length)
Boolean({}) wrong, do not use!
true
boolean.js
console.log(Boolean(1)) // true
console.log(Boolean(0)) // false
console.log(Boolean(NaN)) // false
console.log(Boolean('a')) // true
console.log(Boolean('')) // false
console.log(Boolean(null)) // false
console.log(Boolean(undefined)) // false

console.log(Boolean(![].length)) // true, empty array
console.log(Boolean([])) // true, empty array, but logic is wrong! DO NOT USE
console.log(Boolean([1,2])) // true, array not empty, DO NOT USE

console.log(Boolean(!Object.keys({}).length)) // true, empty object
console.log(Boolean({})) // true, empty object, but logic is wrong! DO NOT USE
console.log(Boolean({'a': 1})) // true, object not empty, DO NOT USE

// logical operator
console.log(1 > 2) // false
console.log(1 < 2) // true

const myBool1 = true // no "quote" needed
const myBool2 = false // no "quote" needed
console.log(myBool1) // true
console.log(myBool2) // false

Code for this tutorial on github.

Summary

  • Boolean only has two value true and false.
  • Special Boolean output table is important to remember.