Like many people, I frequently use IIFEs, but hate the way they look (especially what Crockford calls "dog balls"):
(function animate() {
requestAnimationFrame(animate);
graphics.render();
})();
This can be slightly improved using void
(though people often use a bang instead):
void function animate() {
requestAnimationFrame(animate);
graphics.render();
}();
I normally define a helper named iife
that just takes a function and calls it, so I can do this kind of thing:
iife(function animate() {
requestAnimationFrame(animate);
graphics.render();
});
This works fairly well, except that it's still a bit noisy, and I now have to define (or import) this weird, little helper function at the top of half of my modules.
We could plausibly standardize the iife
function and make it global, but I'd like to propose something else.
A generalized invocation operator, like the do
operator from CoffeeScript, would be a bridge too far. It was often misused, so you'd regularly see CoffeeScript code like this:
gain = do audioContext.createGain
That said, a more limited do-function grammar that must define the function that is being immediately invoked would be very nice to have. Something like this:
do function animate {
requestAnimationFrame(animate);
graphics.render();
}
Note: The function name (animate
in the example) is (generally) optional, while the parens (around params) would always be omitted (as above), as they are redundant.
I'm not sure there's any need to support a do-class equivalent (I cannot think of a single usecase for an immediately invoked class expression, and want to avoid generalizing do
). However, supporting immediately invoked async-functions and generators does seem helpful. The grammar would be obvious:
do async function { ... }
do function * { ... }
Arrow functions would work the same way:
const toggle = do => {
const element = document.querySelector(selector);
return (name) => element.classList.toggle(name);
};
Having a limited grammar also prevents confusion with the (existing, but generally avoided) do-while grammar and the (proposed, and frankly, horrible) do-expression grammar.