DEV Community

Ngan Kim Khong
Ngan Kim Khong

Posted on

Javascript true false weirdness

Recently I was trying to check true/false value for an object. I was pretty sure that an empty object is set to true in Javascript (as well as an empty array).
However, when comparing an empty object to true, I always get false.
Alt Text
This was spotted quite late into my Javascript journey, so I would like to share it here

Top comments (5)

Collapse
 
eljayadobe profile image
Eljay-Adobe •

The === equality check is a strong check. If something is truthy is does not necessarily equality-check to true.

Most everything in JavaScript is truthy. The 8 things that are falsy are:

  • false
  • 0
  • ""
  • null
  • undefined
  • -0 (I know, that's underhanded, but -0 is slightly different than 0)
  • NaN
  • document.all (in the HTML context)

Things that are truthy that occasionally mess people up:
var b = new Boolean(false)
var a = []
var o = {}

Collapse
 
nk2303 profile image
Ngan Kim Khong •

Thank you for the concept! Wow. It's really concise and simple, yet can give me great bugs if not careful :)

Collapse
 
bias profile image
Tobias Nickel •

and what is weired about it? I think it is super helpful. in the beginning I wrote something like this:

if (obj.prop !== undefined && obj.prop !== null) {
   ...
}

today I do

if (obj.prop) {
   ...
}

I think this is awesome.

and with the new optional chaining operator this get even better.

Collapse
 
nk2303 profile image
Ngan Kim Khong •

I was confused because if "an obj is true", then "obj === true" should return true, yet I got false. At least to my humanly logic, lol. I thought something wrong with my logic until I realized it was just the equal sign.

Collapse
 
perpetualwar profile image
Srđan Međo •

You need better understanding of truthy and falsy values in js... And what is object and what is boolean.