Technical skill practice

Anonymous Functions in JavaScript: Pass a Callback or Call It

An anonymous function expression can create a function without an explicit name in its syntax. Pass that function value when another operation should call it later; calling it first passes its result instead.

The task

Create a badge formatter, send it to a callback runner and compare its reference with the text returned by invoking it.

Runnable Node 22 example

const assert = require('node:assert/strict');

const formatter = function (label) { return `[${label}]`; };
function run(callback, value) { return callback(value); }
assert.equal(typeof formatter, 'function');
assert.equal(run(formatter, 'new'), '[new]');
assert.equal(typeof formatter('new'), 'string');
assert.equal(formatter.name, 'formatter');
assert.throws(() => run(formatter('new'), 'again'), TypeError);
console.log(run(function (label) { return label.toUpperCase(); }, 'ready'));

Expected output and explanation

formatter is the callable value, while formatter("new") is the resulting string. The runner expects a callable value, so receiving that string produces the asserted TypeError. The inline expression passed in the final call is invoked by run and prints READY.

The name assertion demonstrates an inferred name from the assignment even though the expression has no explicit function name. “Anonymous syntax” does not guarantee that diagnostic tools show a blank name. This is a property of the actual assignment tested here, not a rule for every expression position.

Output from the example

READY

Pitfall to check

A function expression and an arrow function are not interchangeable for every this or arguments requirement. Choose the form from the callback’s needs. Captured state is a separate closure topic; this formatter does not maintain private evolving state.

Questions, answered

Should I write formatter or formatter() when supplying a callback?

Supply formatter when the receiver should call it. Use formatter() only when the receiver is meant to get the result of that immediate call.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.