commits by Kevin Holditch

Menu

Tag Archives: javascript falsy values

Having read Douglas Crockford’s fabulous Javascript the good parts book I wanted to point out one of the biggest gotchas in JavaScript… Which values are false?

There are 6 values that evaluate to false in JavaScript, EVERYTHING else will evaluate to true. The 6 falsy values in JavaScript are:

0 – the number 0

NaN – not a number)

” – the empty string

false – the boolean value false

null

undefined

This can lead to some surprising values being true for example:

if ('0') { // this is true
if ('false') { // this is true
if (' '){ // this is true

The top value is true because we are testing the string 0 not the number 0. The second one is true because we are testing the string ‘false’ and not the Boolean false. The last one is true because the string is not empty – it has a single space character.

So remember if you are not dealing with one of the 6 values above then the answer is true… simples!