What are false and true in Javascript?

Posted in Articles

Tweet This Share on Facebook Bookmark on Delicious Digg this Submit to Reddit

Falsy in Javascript

In Javascript, these are considered falsy …

  • boolean false
  • ” – empty string
  • 0 – number zero
  • NaN – Not a Number
  • undefined
  • null

When placed in an if-branch, it results in a false condition…

null is falsy

null is falsy

However, null is not equivalent to false …

null is not equivalent to false

null is not equivalent to false

In fact null and undefined are not equivalent to anything except for themselves…

null and undefined

null and undefined

NaN is not equivalent to anything including itself…

NaN not equivalent to anything

NaN not equivalent to anything

Truthy in Javascript

Everything else is truthy.  So that means that some things that seem like they should be falsy are actually truthy.

For example, these all are truthy…

  • {} – empty object
  • “0” – the string “0”
  • “false” – the string “false”

A function definition (empty or not and with return statement or not) is truthy.

function definition is truthy

function definition is truthy

A function call that returns undefined is falsy …

function returning undefined is falsy

function returning undefined is falsy

A function that has just a return statement, actually returns an undefined.

Is Empty Array Truthy or Falsy?

An empty array by itself is truthy…

empty array is truthy

empty array is truthy

Unless it is in a comparison …

empty array in comparison

empty array in comparison

in which case it compares positively to false.  This is because the comparison causes all elements of the array to be convert to string and then concatenated resulting in a empty string “” for an empty array, which is falsy.