philihpAboutPGPLightning

Calling with Commas in Javascript

Philihp Busby,1 min read

If you want to call something multiple times, it’s easy

const f = () => console.log("f() called"); f(); // f() called f(); // f() called f(); // f() called

But that’s so basic. You can also do it this way.

[1, 2, 3].forEach(f); // f() called // f() called // f() called // => undefined

But those constant literals there are clouding up the whole business. Gross, but we can remove them!

[, ,].forEach(f); // => undefined

But wait! f() isn’t called for every element, then! What gives? There’s a hint here if we use Array.map instead…

[, ,].map(f); // => [ <2 empty items> ]

It’s because of copy elision  here. But if we use Ramda#map , it does work.

const R = require("ramda"); R.map(f, [, ,]); // f() called // f() called // => [ undefined, undefined ]

But it’s only called twice! What gives? This is because of trailing commas in arrays . It’s a feature, not a bug.

const R = require("ramda"); const ff = R.map(f); ff([, , ,]); // f() called // f() called // f() called // => [ undefined, undefined, undefined ]

Enjoy your job security!

GitHub · Bluesky · LinkedIn · Instagram · KeybaseRSS

Built from 8f0906ac CC BY 4.0 — with love from San Francisco.