Truthy & Falsy Values

In the previous section, we learned about the strict and loose equality in JavaScript. Equality always results in a boolean value, it can either be a boolean true or a boolean false.

Unlike other languages, true and false values are not limited to boolean data types and comparisons. It can have many other forms.

In JavaScript, we also have something known as truthy values and falsy values.

Truthy expressions always evaluate to boolean true and falsy evaluate to boolean false.

Knowledge of truthy and falsy values in JavaScript is a must, if you don't know which values evaluate to truthy and which to falsy, you're going to have a hard time reading other people's code.

Longtime JavaScript developers often toss around the terms "truthy" and "falsy", but for those who are newer to JavaScript these terms can be a bit hard to understand.

When we say that a value is "truthy" in JavaScript, we don't just mean that the value is true. Rather, what we mean is that the value coerces to true when evaluated in a boolean context. Let's look at what that means.

The easiest way to learn truthy and falsy values is to memorise falsy values only. There are only six falsy values, all the other values are truthy.

Let's explore the list of falsy values:

FALSY

  • false
  • 0 (zero)
  • "", '', `` (empty strings)
  • null
  • undefined
  • NaN (not a number)

note : Empty array ([]) is not falsy

TRUTHY

  • Everything that is not FALSY

That's a pretty straightforward list. But how can we actually use truthiness? Let's look at an example.

Taking advantage of truthiness can make your code a little bit more concise. We don't need to explicitly check for undefined"", etc. Instead we can just check whether a value is truthy. However, there some caveats to keep in mind.

I hope this introduction to truthiness and falsiness helps you to write clearer, more concise JavaScript.

https://www.sitepoint.com/javascript-truthy-falsy/

Complete and Continue