StoicBuilder

HandbookI the LudusNull and undefined

Ithe Ludus, Read code

Null and undefined

1 min readUpdated 28 November

In plain words

In JavaScript, undefined means a value was never set and null means it was set to empty on purpose; reading a property from either one throws an error.

Where you see it

The most common red error in React apps: "Cannot read properties of undefined (reading 'name')". A Guildhall profile page draws itself before the member's data arrives, and member is still undefined when the code asks for member.name.

src/lib/members.tsbrowser
const member = members.find((m) => m.id === id); // undefined if no match member.name; // TypeError: Cannot read properties of undefinedmember?.name; // undefined, no crashmember?.name ?? "Unknown"; // "Unknown"
?. stops at null or undefined. ?? supplies a fallback.

What goes wrong

  1. Drawing the page before the data arrives

    On the first render, data from Supabase isn't there yet. Code that reads user.name straight away takes the whole page down.

    <h1>{user.name}</h1>
  2. Covering every crash with optional chaining

    Optional chaining stops the crash but can leave a blank where a name belongs. Decide what the person should see instead: a loading state, a fallback or a clear message.

  3. Treating 0 or "" as missing

    || replaces anything falsy, so a price of 0 becomes the fallback. ?? replaces only null and undefined.

    const price = item.price || 4.99; // a free item now costs 4.99

What to tell your agent

Copy this into Lovable, Bolt, Cursor or any agent
Handle two cases for every value on this page that comes from Supabase or a fetch call: still loading, and null. Use ?? rather than || for fallbacks, and describe what the user sees in each case.

Quick check

Sign in to earn +10 XP for it

A free side dish has price 0 in the database, but QuickBite shows 4.99. The code says item.price || 4.99. Why?

Got a prompt that touches null and undefined?

Paste it. You get a better prompt first, then the cards that explain it.

Check your own prompt

Free, no sign-up.