Skip to content
JavaScript: Give each array row its own mutable state

JavaScript: Give each array row its own mutable state

November 16, 2026

A scheduler needs one job list per worker. Filling an array with one object gives every worker the same list. Create the object and its nested list inside a factory callback.

Set up

Tested on Debian 13 Linux with Node.js v24.22.1. Use Bash, Node.js on your PATH, a text editor, and the mktemp, rm and rmdir utilities. No packages or network access are needed. Keep the same terminal through cleanup. Stop if setup fails before saving the source.

start_dir="$PWD"
work_dir="$(mktemp -d)" || exit 1
cd -- "$work_dir" || exit 1

Run the example

Save as javascript-independent-array-rows.mjs:

import assert from 'node:assert/strict';

const shared = Array(3).fill({ jobs: [] });
shared[0].jobs.push('compile');
assert.equal(shared[0], shared[1]);
console.log(`filled: ${JSON.stringify(shared.map((row) => row.jobs))}`);

const rows = Array.from({ length: 3 }, () => ({ jobs: [] }));
rows[0].jobs.push('compile');
assert.notEqual(rows[0], rows[1]);
assert.notEqual(rows[0].jobs, rows[1].jobs);
assert.deepEqual(rows.map((row) => row.jobs), [['compile'], [], []]);
console.log(`factory: ${JSON.stringify(rows.map((row) => row.jobs))}`);

const template = { jobs: [] };
const shallow = Array.from({ length: 3 }, () => ({ ...template }));
shallow[0].jobs.push('test');
assert.notEqual(shallow[0], shallow[1]);
assert.equal(shallow[0].jobs, shallow[1].jobs);
console.log(`shallow: ${JSON.stringify(shallow.map((row) => row.jobs))}`);

Run:

node javascript-independent-array-rows.mjs

Observed output:

filled: [["compile"],["compile"],["compile"]]
factory: [["compile"],[],[]]
shallow: [["test"],["test"],["test"]]

Read the result

The first assignment changes every entry because all three slots contain the same object. The factory creates a new object and a new jobs array for each slot. Spreading the template creates distinct outer objects that still share the template’s nested array.

Apply it carefully

Allocate each mutable field inside the factory when rows must be independent. A factory that returns one existing object still shares it. Filling with a primitive value such as zero is appropriate when each slot only needs that value. This example does not clone arbitrary class instances or handle resource ownership.

The ECMAScript specification defines fill as repeated assignment of the supplied value and Array.from with a mapping callback.

Clean up

Remove the saved file and empty scratch directory. If the directory is not empty, inspect its contents before removing anything else.

rm -- javascript-independent-array-rows.mjs
cd -- "$start_dir" || exit 1
rmdir -- "$work_dir"
unset start_dir work_dir

Acknowledgements

This post was created with assistance from AI.

Last updated on