Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 1

Immutable nested update (setIn) in JavaScript

106 an immutable update that shares what it did not change

fair

Write setIn(state, path, value) that returns a new state with one deep value replaced, and updateIn(state, path, fn) built on top of it. Copy only the objects along the path, share everything else, and show that it works on a frozen object where a plain assignment throws.

Stuck? Three hints, smallest first
  1. 1. Recurse on the head of the path: { ...target, [head]: setIn(target[head], rest, value) }. The base case is an empty path.
  2. 2. An array on the path has to come back an array, so branch on Array.isArray and copy with a spread rather than object-spreading it.
  3. 3. Check identity, not contents, to see what was copied: next.cart === state.cart is the assertion that proves you shared the untouched branch.

The answer

const segments = (path) => (Array.isArray(path) ? path : String(path).split('.'));

const setIn = (target, path, value) => {
  const [head, ...rest] = segments(path);
  if (head === undefined) return value;                       // the base case: replace it all
  const nested = rest.length ? setIn(target?.[head] ?? {}, rest, value) : value;
  if (Array.isArray(target)) {
    const copy = [...target];
    copy[Number(head)] = nested;
    return copy;
  }
  return { ...target, [head]: nested };
};

const getIn = (target, path) => segments(path).reduce((acc, key) => acc?.[key], target);
const updateIn = (target, path, fn) => setIn(target, path, fn(getIn(target, path)));

const state = {
  user: { name: 'Amaka', address: { lga: 'Yaba', city: 'Lagos' } },
  cart: { items: [{ sku: 'GRP-1', units: 2 }, { sku: 'GRP-2', units: 1 }], note: 'gate 3' },
};

const moved = setIn(state, 'user.address.lga', 'Surulere');
const pathIsNew = [moved !== state, moved.user !== state.user, moved.user.address !== state.user.address];
const restIsShared = [moved.cart === state.cart, moved.user.name === state.user.name];

const restocked = setIn(state, 'cart.items.0.units', 5);
const arrayShape = [Array.isArray(restocked.cart.items), restocked.cart.items[0].units, state.cart.items[0].units];
const otherItemShared = restocked.cart.items[1] === state.cart.items[1];

const bumped = updateIn(state, 'cart.items.0.units', (n) => n + 10);
const created = setIn(state, 'user.bank.name', 'GTBank');

const frozen = Object.freeze({ vendor: { name: 'Ngozi Traders' }, tier: 1 });
const promoted = setIn(frozen, 'tier', 2);
let writeError = 'no error';
try { frozen.tier = 2; } catch (e) { writeError = e.constructor.name; }

const wholesale = setIn(state, [], 'replaced entirely');

console.log('moved  :', moved.user.address, '| original:', state.user.address);
console.log('shared :', restIsShared, '| path copied:', pathIsNew);
console.log('array  :', arrayShape, '| sibling shared:', otherItemShared);
console.log('frozen :', promoted.tier, frozen.tier, writeError);

Output


      
9 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('the new state holds the new value and the old one is unchanged', [moved.user.address.lga, state.user.address.lga], ['Surulere', 'Yaba']);
test('every object along the path is a new object', pathIsNew, [true, true, true]);
test('and everything off the path is the very same object, not a copy', restIsShared, [true, true]);
test('an array on the path comes back an array, with one item replaced', arrayShape, [true, 5, 2]);
test('its siblings are shared, so a big list costs one new array and one new item', otherItemShared, true);
test('updateIn reads the old value first and writes what the function returns', [bumped.cart.items[0].units, state.cart.items[0].units], [12, 2]);
test('a path through nothing builds the objects it needs', [created.user.bank.name, Object.keys(created.user)], ['GTBank', ['name', 'address', 'bank']]);
test('it works on a frozen object, since it never writes to one, while the assignment throws', [promoted.tier, frozen.tier, writeError], [2, 1, 'TypeError']);
test('an empty path replaces the whole thing, which is the recursion base case', wholesale, 'replaced entirely');

This is structural sharing, the idea every immutable-state library is built on. The new state is not a copy of the old one: it is a new object per level along the path, pointing at the same objects everywhere else. Replacing one item in a thousand-item cart allocates one array and one object, not a thousand.

The identity assertions are the ones to internalise, because they are what makes change detection cheap. A component holding the old state.cart can compare it by reference to the new one and skip re-rendering in a single ===, with no deep walk. That is also why mutating in place breaks these libraries: the reference stays equal, so nothing notices.

Two costs. setIn will happily build a branch out of a typo in the path, so a wrong path is an unnoticed new key rather than an error. And it never writes, which is why it works on a frozen object while frozen.tier = 2 throws — in strict mode, which is how these panels run. Outside strict mode that same assignment would fail silently, which is the real argument for strict mode.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.