Skip to content

Truthy / Falsy

In JavaScript, a truthy or falsy value is a value that is being casted into a boolean when evaluated in a boolean context. An example of boolean context would be the evaluation of an if condition:

Every value will be casted to true unless they are equal to:

  • false
  • 0
  • "" (empty string)
  • null
  • undefined
  • NaN

Here are examples of boolean context:

  • if condition evaluation
if (myVar) {}

myVar can be any first-class citizen (variable, function, boolean) but it will be casted into a boolean because it's evaluated in a boolean context.

  • After logical NOT ! operator

This operator returns false if its single operand can be converted to true; otherwise, returns true.

1
2
3
!0 // true -- 0 is falsy so it returns true
!!0 // false -- 0 is falsy so !0 returns true so !(!0) returns false
!!"" // false -- empty string is falsy so NOT (NOT false) equals false
  • With the Boolean object constructor
new Boolean(0) // false
new Boolean(1) // true
  • In a ternary evaluation
myVar ? "truthy" : "falsy"

myVar is evaluated in a boolean context.

Be careful when comparing 2 values. The object values (that should be cast to true) is not being casted to Boolean but it forced to convert into a primitive value one using ToPrimitives specification. Internally, when an object is compared to Boolean value like [] == true, it does [].toString() == true so...

1
2
3
let a = [] == true // a is false since [].toString() give "" back.
let b = [1] == true // b is true since [1].toString() give "1" back.
let c = [2] == true // c is false since [2].toString() give "2" back.

External resources