logical or assignment

When I write code I don’t expect it to ever have an audience; I’m not accustomed to sharing or collaborating on a codebase. I’m also guilty of refactoring and rewriting everything while I write it rather than planning ahead or saving small issues for a full review at a good milestone. I like to think I’m getting better at this but I’ll often reach for terse snippets instead of clean, readable examples.

In that vein here’s a neat, new-ish JavaScript pattern I always want to use but usually forget.

Sometimes you want to

  1. append to an array if it exists
  2. or if it doesn’t

I used to write something like

const o = {};
const key = 'a';
const x = 'new value';

if (o[key]) {
o[key].push(x);
} else {
o[key] = [x];
}

with the new logical assignment operators in ES2021, that last bit could be cut down to the un-grokkable but attractively short:

(o.key ||= []).push(x);

This initializes o.key to [] if it hasn’t been done already and then pushes onto the result.