Sunday, January 26, 2014

Six falsy values in JavaScript

There are Six falsy values in JavaScript:
·         undefined
·         null
·         false
·         ""
·         0
·         NaN    
All values in JavaScript become true when converted to a boolean, with the exception of the above six falsy values. If the variable mynumber is defined, its value is kept. Otherwise, it's initialized with the value 10.

var mynumber = mynumber || 10;

This is simple and looks elegant, but be aware that it is not completely bulletproof.
If mynumber is defined and initialized to 0 (or to any of the six falsy values), this code might not behave in exactly the way it was designed to work.

var m = 100; var m = m || 10; m; //100

var m1 = null; var m1 = m1 || 10; m1; //10