Truthy or Falsy?

Grace Yuiko Nakano
2 min readSep 7, 2021

Understanding the essential JavaScript Concepts of truthy and falsy values

When we hear the “truthy” and “falsy”, we automatically associate these terms to the boolean context. So what makes them different from the boolean, “true” and “false”? In JavaScript, these values are taken one step further and evaluated in a boolean context.

To delve deeper into understanding these values that evaluate to true or false, it is important to note that there are only six falsy values:

  1. undefined
  2. “” (an empty string)
  3. null
  4. NaN
  5. 0
  6. false
let name = "" //=> falsy
let name = "Grace" //=> truthy

When the variable name is set to an empty string, it evaluates to a falsy value but if we set the variable name to something, it will evaluate to a truthy value.

Let us observe falsy values within a function. We have our fizz_buzz function that, between numbers 1 and 100, prints “fizz” for every 3, “buzz” for every 5, and “fizz buzz” for every 3 and 5, or returns the index number. In order to evaluate these values, we use modulus to determine the return value.

function fizz_buzz() {
for(i = 0; i < 100)
console.log((++i % 3 ? "" : "fizz") && (i % 5 ? "" : "buzz") || i)
}

We are iterating through the index, starting at 0, and returning an incremented value through each iteration. When the increment operator is placed before the operand, it ensures that it returns the incremented value before evaluating the expression. So setting i = 0 ensures that the first console log to iterate is ++0, which is 1 % 3. What does i modulus 3 evaluate to? We have the condition if true : condition if false.

NB: Modulus is the remainder after the division.

3 % 3 evaluates to 0, as it has no remainder. Because 0 is a "falsy value", it will evaluate to false, returning "fizz"

4 % 3, evaluates to 1, which is a truthy value. Because it evaluates true, it will return "" || i, returning the index number.

We can always take a truthy or falsy value to evaluate a boolean by using JavaScript’s “!!” logical operator.

let name = ""
console.log(!!name) // => false
let greeting = "hello"
console.log(!!greeting) // => true

Evaluating truthy and falsy values is valuable when filtering through an array of values, which may include falsy values that you would like to filter out.

let array = ['Grace', '', 'software engineer', 0, false]
console.log(array.filter(Boolean)
// => ['Grace', 'software engineer']

--

--

Grace Yuiko Nakano

Fullstack Software Engineer | Musician | Food Lover | Coffee Addict