JavaScript by Example

Booleans

Booleans represent yes or no with the values true and false.

A boolean answers a yes or no question. It has only two possible values: true and false.

You can write a boolean directly or create one by comparing values. Store the result in a clearly named variable, then use it to decide what your program should do. && means "and": both values must be true. ! means "not": it reverses a boolean value.

const isLoggedIn = true;
const hasErrors = false;
 
const age = 20;
const isAdult = age >= 18;
console.log(isAdult); // true
 
const hasTicket = true;
if (isAdult && hasTicket) {
  console.log("Welcome in");
}
 
console.log(!hasTicket); // false

In production

Give boolean variables names that read like questions, such as isAdult, hasTicket, or canEdit. Use === and !== for equality checks because they do not convert values to different types before comparing them.

Enjoyed this? Get more software craft delivered to your inbox.