Truthy and Falsy Values In JavaScript

In JavaScript, every value is considered either “truthy” or “falsy.” These terms help us understand how JavaScript decides if a value is true or false when it’s not exactly a true or false value. This concept is super handy for making decisions in our code. Let’s break it down so it’s easy to get.

What Are Falsy Values?

Falsy values are simple. They are just a few specific values that JavaScript looks at as false whenever it needs a true or false answer. There are not many of them, so they’re easy to remember. Here they are:

  1. false – Yep, false itself is, of course, falsy.
  2. 0 – The number zero.
  3. "" or '' (empty string) – A string with nothing in it.
  4. null – This means “no value.”
  5. undefined – This means a variable hasn’t been given a value yet.
  6. NaN – Stands for “Not a Number,” which you get from math gone wrong.
if (false) { /* This code won't run because false is falsy. */ }
if (0) { /* This code won't run because 0 is falsy. */ }

What Are Truthy Values?

Truthy values are basically everything else that’s not in the falsy list. This means almost everything in JavaScript is truthy! If you use a value in a place where JavaScript is expecting true or false, and it’s not one of those six falsy values, JavaScript treats it as true.

if ("hello") { /* This code runs because "hello" is truthy. */ }
if (42) { /* This code runs because 42 is truthy. */ }

Even if something seems weird or empty, like an empty object {} or an empty array [], it’s still considered truthy in JavaScript.

Why Does This Matter?

Understanding truthy and falsy values is super important for making decisions in your code. For example, you might want to check if a user has entered something in a form field:

let userName = "";

if (userName) {
  console.log("Hello, " + userName);
} else {
  console.log("Please enter your name.");
}
// This will log "Please enter your name." because an empty string is falsy.

Quick Tip

A cool trick in JavaScript is using !! before a value to check if it’s truthy or falsy. The first ! turns a truthy value to false and a falsy value to true. The second ! flips it back, giving you true for truthy values and false for falsy values.

console.log(!!"hello"); // true because "hello" is truthy
console.log(!!0); // false because 0 is falsy

Conclusion

In JavaScript, values can be truthy or falsy, which helps the language decide what’s considered true or false in different situations. Remembering the few falsy values can go a long way in making your code work the way you want. And remember, when in doubt, you can always use !! to quickly check if something is truthy or falsy.