Calling Back When Something Happens
You’ll port the Learn to Boulder class’s two callbacks: a warning when its two places fill, and a
reminder before it ends. Python’s make_session() defaults the warning callback to None and checks
on_full is not None before calling it. What does JavaScript do instead of that check?
In JavaScript, the factory and its warning port line by line; with no keyword arguments, the
warning travels in an options object. Where Python uses None, JavaScript usually gives an
optional callback a do-nothing default: an empty arrow, () => {}. The outer braces pull onFull
out of the options, which default to an empty object, = {}. So the check drops out, and the
check-in calls onFull(name) without asking:
function makeSession(
name,
prefix,
places,
{ onFull = () => {} } = {},
) {
const climbers = [];
return (climber) => {
climbers.push(climber);
if (climbers.length === places) {
onFull(name);
}
return `${prefix}-${100 + climbers.length} ${climber}`;
};
}
const announceFull = (name) =>
console.log(`${name} is full`);
const intro = makeSession("Learn to Boulder", "L", 2, {
onFull: announceFull,
});
console.log(intro("Mia Novak"));
console.log(intro("Leo Park"));
With no option, the empty arrow runs, and nothing happens. Run the port, and Leo’s warning lands before his wristband, as in Python: