In JavaScript, ‘true’ == true is false, truthy truth

Somehow, I had thought that in JavaScript that if I said ‘true’ == true that a string conversion to bool would happen on the left side of the comparator and that the == instead of the truthy === would do a type conversion for me.

Apparently not.

So, for now on, all my JavaScript will look like this when I’m saving off a boolean that I collect in string form.

 var donationConfirmed = 
  $('#RegisterUserInfoLoggedIn_DonationConfirmed').
      val().toLowerCase() === "true";

Happy to hear why I’m wrong here but I don’t think I am.

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP for the past 7 years. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


Comments

  1. I think it’s converting to numbers first …
    true -> 1 -> ‘1’
    ‘true’ != ‘1’ hence false

    You don’t need to use ‘===’ over ‘==’ in that case as both values are strings, so no type coercion will happen. On the other hand, it doesn’t hurt. :-)

  2. Peter Kellner says:

    nice, very clever! thanks.

  3. If you want to coerce a type to boolean, you can use !!. The first NOT forces type coercion to boolean and the second NOT flips it back to the original value. In other words, this is true:

    !!’true’ === true;

Follow

Get every new post delivered to your Inbox

Join other followers: