Brock Nash Brock Nash

Brock’s Operator: Conditional Spreading in JavaScript

A small JavaScript helper for conditional spreading: include one value when present, or no values when nullish.

Sometimes an array—or a list of DOM children—has an optional item. The idea behind Brock’s Bread Spread Programming Operator is to turn that item into something that can be spread: one item when it is present, no items when it is absent.

One item, or none

For a helper that treats only null and undefined as absent, the implementation is:

const __ = item => item == null ? [] : [item];

This preserves meaningful values such as 0, false, and an empty string. A present value becomes a one-element array; a nullish value becomes an empty array.

Spread the optional ingredient

const ingredients = ['bread', 'peanut butter', ...__(optionalJelly)];

container.append(label, ...__(optionalButton));

The spread syntax expands either one item or no items, keeping the optional case close to the expression it belongs to.

A small syntax detail

The original experiment uses [item] ?? []. Because [item] is always an array, that expression never reaches the fallback—even when the item is null. Checking the item before wrapping it expresses the intended behavior.

Visit the original Brock’s Operator experiment →

The original page remains available as an archive of the idea.

Read More