All Posts
Tips

5 JavaScript Tips I Wish I Knew Earlier

October 28, 2024

After years of writing JavaScript, I've collected a few patterns that I keep coming back to. Here are five of my favorites.

1. Optional Chaining

// Instead of:
const name = user && user.profile && user.profile.name;

// Use:
const name = user?.profile?.name;

2. Nullish Coalescing

const port = config.port ?? 3000;

3. Object Destructuring with Defaults

const { name = 'Guest', role = 'viewer' } = user;

4. Array.at() for Last Item

const last = arr.at(-1); // cleaner than arr[arr.length - 1]

5. Promise.allSettled()

Use this when you want all promises to finish regardless of success or failure, then handle each result individually.