Last Updated: May 31, 2021
·
1.188K
· gerardsans

JavaScript falsy objects and comparisons

Sons of JavaScript Collection | this article

In JavaScript you will find yourself scrapping your head around comparisons and perplexed about what is true and false. This is because JavaScript uses truthy and falsy comparisons.

Falsy objects (meet the family)

empty string, the number 0, null, NaN, a boolean false, and undefined 

Truthy objects are just anything else that is not falsy. Basically any object that is initialised with any value different from the blacklist.

Comparisons

JavaScripts evaluates comparisons from left to right. This is for efficiency so as soon as there is a reason to stop evaluating expressions JavaScript will do so.

As a general rule OR comparisons will stop as soon a truthy expression is evaluated. AND comparisons will stop as soon as a falsy expression is evaluated.

function Fn1() {console.log("Fn1");}
function Fn2() {console.log("Fn2");}

if (true || Fn1() || Fn2())
  console.log("Or"); // Fn1 and Fn2 never get called

if (false && Fn1() && Fn2())
  console.log("And"); // Fn1 and Fn2 never get called

// only "Or" is logged

OR comparisons ||

// if value is falsy setting = default
var setting = value || default; 

AND comparisons &&

//if value is falsy setting = false otherwise setting = Fn()
var setting = value && Fn(); 

Not operator !

It converts objects to booleans. If the object is falsy it returns true otherwise false.

function Increment(a) {
  if (!a) return; // if a is falsy !a evaluates to true
  return a++;
}

Sons of JavaScript Collection | this article