map vs flatMap in Effect (Learning Effect, Part 4)

By Esteban Trillo2 min readupdated Learning EffectEffectTypeScript

Ask what the callback returns. A value means map, an Effect means flatMap.
Ask what the callback returns. A value means map, an Effect means flatMap.

I kept mixing up map and flatMap.

The rule is simple.

Use map when the callback returns a plain value.

Use flatMap when the callback returns an Effect.

That is it.

The same names in plain TypeScript

Arrays have both operators too.

const names = ["ada lovelace", "grace hopper"];
names.map((name) => name.split(" "));
// [["ada", "lovelace"], ["grace", "hopper"]]
names.flatMap((name) => name.split(" "));
// ["ada", "lovelace", "grace", "hopper"]

The callback returns an array.

map keeps the nesting.

flatMap flattens it.

Effect works the same way. Swap the array for an Effect.

Promise.then hides this. It flattens whatever you return, so you never had to pick.

Effect makes you pick.

That felt like extra work at first. Now it tells me what kind of step I am writing.

map changes the value

const program = Effect.succeed("ada").pipe(
Effect.map((name) => name.toUpperCase()),
);

toUpperCase() returns a plain string.

So this is map.

Should this use map or flatMap? name => name.toUpperCase()

flatMap continues the program

const program = parseUserId("1").pipe(Effect.flatMap((id) => fetchUser(id)));

fetchUser(id) returns an Effect.

So this is flatMap.

Should this use map or flatMap? id => fetchUser(id)

The smell

If you use map with a function that returns an Effect, you get an Effect inside an Effect.

Effect.Effect<Effect.Effect<User, UserNotFound, never>, InvalidUserId, never>;

That type is trying to tell you something.

You probably wanted flatMap.

What usually caused Effect inside Effect?

The other direction

The reverse mistake is louder.

const program = Effect.succeed("ada").pipe(
Effect.flatMap((name) => name.toUpperCase()),
);

flatMap expects the callback to return an Effect.

This one returns a string.

toUpperCase() gives back a plain value, so map was the right tool.

TypeScript stops you here. The error says string is not assignable to Effect.

The nested case is quieter. It compiles.

How to spot it: hover the program in your editor. Two Effect types in a row means nesting.

Both mistakes have the same fix. Look at what the callback returns.

Same question as before.

What I am taking with me

The question is not “which operator do I like?”

The question is:

What does my callback return?

Plain value: map.

Effect value: flatMap.

Piwi hands a single letter to the user at a mailbox; a small note reads no noise.

Get the next one in your inbox

One email when a post goes out, with its sketch. Nothing in between, and one link to leave.

Sign in faster next time?

Add a passkey and skip the email link. Your fingerprint, face or device PIN is enough.