Javascript true false weirdness
Ngan Kim Khong

Ngan Kim Khong @nk2303

About: Hi! I'm currently a software engineer intern! I am looking to post some blogs about what I'm learning :)

Location:
Seattle, WA
Joined:
Feb 22, 2020

Javascript true false weirdness

Publish Date: Aug 24 '20
1 5

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

Comments 5 total

  • Srđan Međo
    Srđan MeđoAug 24, 2020

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

  • Eljay-Adobe
    Eljay-AdobeAug 24, 2020

    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 = {}

    • Ngan Kim Khong
      Ngan Kim KhongAug 30, 2020

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

  • Tobias Nickel
    Tobias NickelAug 25, 2020

    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.

    • Ngan Kim Khong
      Ngan Kim KhongAug 30, 2020

      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.

Add comment