Don’t use functions as callbacks unless they’re designed for it

Solid advice by Jake:

Here’s an old pattern that seems to be making a comeback:

import { toReadableNumber } from 'some-library';
const readableNumbers = someNumbers.map(toReadableNumber);

Here’s the problem:

// We think of:
const readableNumbers = someNumbers.map(toReadableNumber);
// …as being like:
const readableNumbers = someNumbers.map((n) => toReadableNumber(n));
// …but it's more like:
const readableNumbers = someNumbers.map((item, index, arr) =>
  toReadableNumber(item, index, arr),
);

You might have encountered this yourself when combining map with parseInt, as its second parameter defines the base to use 😅

Don’t use functions as callbacks unless they’re designed for it →

map is one of the array methods I use a lot, along with filter and reduce. This post right here explains them using a simple example.

Published by Bramus!

Bramus is a Freelance Web Developer from Belgium. From the moment he discovered view-source at the age of 14 (way back in 1997), he fell in love with the web and has been tinkering with it ever since (more …)

Leave a comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.