View profile

Nullish Values in JavaScript

JavaScript developers often implicitly rely on truthy and falsy checks when writing if statements:
Nullish Values in JavaScript
By Mastering JavaScript Tutorials • Issue #14 • View online
JavaScript developers often implicitly rely on truthy and falsy checks when writing if statements:

Do you really want to skip `doStuff()` if `v` is an empty string?
Do you really want to skip `doStuff()` if `v` is an empty string?
Unfortunately, the notions of truthy and falsy rarely capture the exact set of values you want to include or exclude from your if statement. There are exactly 7 values that are falsy in JavaScript:
  • 0 as a number
  • 0 as a BigInt
  • false
  • null
  • undefined
  • Empty string
  • NaN
Every other value is truthy. In particular, every object is truthy. The original notion of falsy and truthy likely goes back to the early days of form validation: falsy is a good substitute for “the values that are OK to enter into a string input field.”
But these days, JavaScript is used for much more than validating string inputs. Too often JavaScript developers use truthy/falsy checks when they really just want to safely access a property without triggering a TypeError.
That’s where the notion of a nullish value comes in. There are 2 nullish values in JavaScript:
  • null
  • undefined
You can check if a value is nullish using `== null`. Yes, using double equals as opposed to triple equals. One neat feature of JavaScript type coercion is that a value is `== null` if and only if the value is null or undefined. ESLint has a rule to allow double equals when comparing against null.
If a value is not nullish, you can safely access its properties
If a value is not nullish, you can safely access its properties
What makes nullish values useful? Because JavaScript only throws a TypeError if you access a property on a nullish value. It is OK to access a property on NaN, 0, or any other falsy value.
So next time you’re tempted to use `if (v)`, think about whether you actually want to skip empty string and 0. Nullish checks are often the better choice.
This Week's Tutorials
Did you enjoy this issue?
Mastering JavaScript Tutorials

Mastering JavaScript Tutorials

If you don't want these updates anymore, please unsubscribe here.
If you were forwarded this newsletter and you like it, you can subscribe here.
Powered by Revue