JavaScript Booleans

A boolean is a data type that can only have two values true or false. In JavaScript, these true and false are not strings but special keywords.

const isActive = true
const isAdmin = false

Expressions as Booleans

Booleans are often used to decide which block of code to execute (conditional statements) or repeat (loops). In these cases, often an expression is used in place the true and false values.

const number = 5

/* if statement */
if (number === 5) { // if the variable number is equal to 5
  // code to execute if the conditional expression is true
}

In the above example, the variable number does equal five, so the expression number === 5 will equal true.

Truthy and Falsy

Some expressions cannot truly be either true or false, but they can take on some of the properties of true or false. Review the following.

const name = 'Michael'
const empty = ''

if (name) { // if the variable name is true
  // code to execute if the conditional expression is true
}

if (empty) {
  // will not execute
}

In the example above, we are asking if the variable name is true or false. But because name is a string, by definition, it cannot be true or false. However, due to type conversion, any non-empty string is perceived to be true. We call such expressions, truthy expressions. Because, while the variable name is not true, JavaScript will act as if it is true. Likewise, an empty string, like the variable empty will be considered false or falsy

In many ways, there is no difference between true and truthy and false and falsy. But, they are NOT identical.

const name = 'Michael'

if (name === true) { 
  // will not execute
}

In the example above, we can see that the variable name while truthy does not equal true.