Tuesday, 13 September 2016

Java Script Falsy Values

Java script is weird. Here is another weird behavior of java script. Like any other programming language Java Script has Boolean data type. But in Java Script any value and any data type can be converted into Boolean. If some one not understand falsy values they might run into trouble. Understanding of falsy values will help you in debugging.

What is falsy?

Any value which will be translated into false is called falsy. Below are the falsy value of Java Script.

  • false
  • 0 (Zero)
  • ""(Empty String)
  • null
  • undefined
  • NaN (It is a Number But Not-A-Number)

1
2
3
4
5
6
console.log(!!(false)) // false
console.log(!!(0)) // false
console.log(!!("")) // false
console.log(!!(null)) // false
console.log(!!(null)) // false
console.log(!!(null)) // false

All other than above values are true in Java Script. You might wonder what about the "0" (Zero in double quotes)? But it is also returns true.


1
console.log(!!("0")) // true

Based on above logic one might think below code will return false.


1
console.log("0" == false) // true

What? "0" is true, true==false should be false. But it is not. This called coercion. It is not bug. It is feature. TO get better understanding look at this "Java Script Coercion".

Above mentioned values are falsy. Each one will behave differently when comes to comparision between then. Look into the compare table of falsy values.

==false0""nullundefinedNaN
falsetruetruetruefalsefalsefalse
0truetruetruefalsefalsefalse
""truetruetruefalsefalsefalse
nullfalsefalsefalsetruetruefalse
undefinedfalsefalsefalsetruetruefalse
NaNfalsefalsefalsefalsefalsefalse


False - Zero - Empty String

The falsy values false, 0 and "" are equivalent when comparing to one another.

1
2
3
console.log(0 == false) // true
console.log("" == false) // true
console.log(0 == "") // true



null and undefined


The falsy values null and undefined is false with all other falsy values except themselves.

1
2
3
4
console.log(0 == null) // false
console.log(0 == undefined) // false
console.log(null == undefined) // true
console.log(null == null) // true


NaN

NaN returns false with any value including NaN itself.


1
console.log(NaN == NaN) // false

Hope you have good understanding on falsy values of Java Script.  

1 comment: