DEV Community

Analogy | Absence | Example
Analogy | Absence | Example

Posted on

Let's talk about "falsiness"

What is falsiness?

If you write a statement where you are testing if something is true or not--like an if statement that uses a logical operator like ||, !, or &&--you expect that statement to return a boolean value of true or false. Sometimes it doesn't resolve to a boolean value--true or false--yet, nevertheless, it gets interpreted like a boolean value. We call those values "truthy" or "falsey".

In Javascript, examples of falsy values are:

  • null
  • undefined
  • NaN (Not a Number)
  • "" (empty string)
  • false
  • 0

Every other value--every value that is not one of the above--will evaluate to true in a Boolean evaluation in Javascript.

Let's go through them one by one. First, I'll demonstrate a variable assignment to each falsy value. Next, I'll show how that falsy value is is interpreted as false using the Boolean() function, which takes a value or expression and always returns either true or false.

null

A variable that resolves to null is a variable that has been deliberately assigned an empty value

let foo = null
console.log(foo) // null

Enter fullscreen mode Exit fullscreen mode

undefined

An undefined variable is a variable that has not yet been assigned a value.

let foo
console.log(foo) // undefined
console.log(Boolean(foo)) // false
Enter fullscreen mode Exit fullscreen mode

NaN

A variable that resolves to NaN can be the result of an invalid math operation, such as 0/0 or sqrt(-1). A number is expected from a math operation, but the expression is invalid, so the result is not a (valid) number.

let foo = 0/0
console.log(foo) // undefined 
console.log(Boolean(foo)) // false
Enter fullscreen mode Exit fullscreen mode

"" (empty string)

Just what it sounds like: a variable that has been assigned to a string with no content.

let foo = ""
console.log(foo) // (actually, nothing shows up)
console.log(Boolean(foo)) // false
Enter fullscreen mode Exit fullscreen mode

false

Just what it sounds like: a variable that has been assigned to a the boolean value false.

let foo = false
console.log(foo) // false
console.log(Boolean(foo)) // false
Enter fullscreen mode Exit fullscreen mode

0

Just what it sounds like: a variable that has been assigned to 0 or that resolves to 0.

let foo = 5 - 5
console.log(foo) // 0
console.log(Boolean(foo)) // false
Enter fullscreen mode Exit fullscreen mode

Top comments (0)