Javascript Quick Tip:
Recognizing Truthy Values in conditional logic

October 9, 2015

My Javascript knowledge, started by learning jQuery. Although I think starting with jQuery is a good way to learn Javascript, in most jQuery tutorials they don't go into the basics of Javascript. And they certainly don't teach you all the different shorthands and nuances there are in Javascript (I'm not saying they should either). If you're learning jQuery or maybe a framework like Angular and you don't have any or much programming experience, it's helpful to understand this basic shorthand for evaluating to true.

if (dogs === true) {} is the same as if (dogs) {}. As a self taught developer, I can speak first hand that this is something that is easily missed in the beginning. Also the following three lines of code are also all the same.

if (dogs === true) {};
if (dogs) {};
if (dogs == 1) {};

Yes, “1” is true when using the loose equality comparison (==). However, 1 is not true when using the strict equality comparison (===) because type coercion is not taking place.

However, I digress. The thing that was really helpful to me is to know that if (dogs) {} is saying, “if dogs is equal to true”. I was in the process of writing a post on Angular’s ng-if directive and realized how important it is to know this shorthand because without it I would be very confused.

Mastering CSS: Book by Rich Finelli
Mastering CSS, the Book! Flexbox, Layout, Animations, Responsive, Retina, and more!
Mastering CSS, 2nd Edition, video course by Rich Finelli
Mastering CSS, Second Edition: 47 videos on how to make websites like a boss! Flexbox, Animations, Responsive, Retina, and more!
  • Harry Goldstein

    I’ve been watching this really excellent video on Packt. Very complete but I prefer books–much easier to ‘stop and think’.
    Will this be available as a book?
    Harry Goldstein
    harry@harryjudee.com

Back to top