JavaScript Object References: Keep Parcel Drafts Separate
Learn how JavaScript reference sharing can corrupt parcel drafts, build a safe factory for nested data, and test isolation before sending orders to fulfillment.

Why Two Parcel Drafts Can Quietly Become One
An order can need multiple parcels, each with different contents, weights, and dimensions. In code, that often turns into an array of draft objects. The array can even have the right number of entries - and still be wrong: if two entries reference the same object, updating one parcel can quietly change the other.
This isn't something to just "watch for" during a code review. It's a data-ownership problem that shows up when an adapter prepares a multi-parcel request for a Shopify fulfillment workflow, a 3PL, or a drop-shipping operation. What happens next varies, but if weight or line items are shared by accident, you can end up with incorrect shipment data.
The practical fix is simple: create each draft - and each editable nested value - independently. This guide breaks down how these reference bugs happen, shows a small parcel-draft factory approach, and demonstrates how to test isolation in Node.js. It also sets a boundary for what the factory should do: prepare local draft state, not validate the order or integrate with a carrier.
Why do parcel drafts change together?
JavaScript objects and arrays are reference values. A variable (or an array entry) can hold a reference to an object rather than a separate copy of all its properties. If two entries point to the same reference, they're effectively sharing one underlying data structure.
The tricky part is that this can look fine at a glance. The array exists and has the length you expected. But two entries don't automatically mean two independently editable parcel drafts.
The fill() trap
Take this pattern:
const template = {
dimensionsCm: { length: null },
items: []
};
const drafts = Array(2).fill(template);
Here, the array contains two references to the same template. JavaScript doesn't "re-run" the object literal for each position. As MDN explains for Array.prototype.fill(), using an object value repeats that same value; it doesn't create a fresh object per slot.
You can see the problem immediately:
drafts[0].dimensionsCm.length = 30;
console.log(drafts[1].dimensionsCm.length); // 30
So the second draft appears to change - because both drafts are really accessing the same parcel data. And that's worse than an obvious crash. A test that only checks drafts.length will pass, and a UI might even render two rows that look separate.
Why a shallow spread is not enough
A common "fix" is to spread the template into a new outer object:
const shallow = Array.from({ length: 2 }, () => ({ ...template }));
Now shallow[0] and shallow[1] are different objects. But the spread is shallow. It copies property values, and when a property value is itself an object or array, that nested value stays shared. So both drafts still share dimensionsCm and items.
This is exactly what hurts when your draft includes editable nested state: a nested dimensions object, an array of line items, package options, customs details - anything with deeper structure. Changing the outer object identity doesn't automatically give you ownership of the nested branches.
A good way to think about it is an ownership graph: start at each parcel draft and follow every property that code might mutate. If two drafts reach the same mutable object or array, their state is coupled. The question isn't just "Did I create two objects?" It's "Did I create separate instances for every mutable node that needs to be independent?"
How do you create independent nested data?
Build each draft inside a factory callback, and create its editable nested objects and arrays inside that same callback. Array.from() with a mapping function is convenient because the callback runs once per array position.
function newParcelDrafts(count) {
if (!Number.isSafeInteger(count) || count < 0 || count > 100) {
throw new RangeError('Expected a draft count from 0 to 100');
}
return Array.from({ length: count }, (_, index) => ({
localSequence: index + 1,
weightGrams: null,
dimensionsCm: {
length: null,
width: null,
height: null
},
items: []
}));
}
Each callback call creates a new outer object, a new dimensionsCm object, and a new items array. Reusing null is fine because null isn't mutable object state. The sequence is computed per entry too, instead of copied from a shared template.
Keep mutable values inside the factory
The placement of those object literals matters. If you define the nested structures outside the callback and reuse them, you bring the sharing bug back:
const dimensions = { length: null, width: null, height: null };
const items = [];
// Avoid: every returned draft shares these nested values.
const drafts = Array.from({ length: 2 }, () => ({ dimensions, items }));
A factory doesn't magically guarantee independence. It just gives you a clean place to allocate the parts that must have separate ownership. Put mutable nested values inside the per-draft creation function, or clone them explicitly when they come from an existing source.
If you're starting from a template, decide how much of the object graph you actually need to copy. A shallow spread can be fine when the values are primitives or you truly want to share immutable references. For editable nested data, it's safer to build the shape directly (or use a cloning approach that matches your real data types and ownership rules). structuredClone() can help for supported types, but it's not a substitute for understanding what your application needs to own separately.
Treat item ownership as a separate decision
An empty items array is independent in the example. But if you seed items with item objects, those objects also need consideration. You can easily end up with two drafts that have different arrays - yet still contain the same mutable line-item object by reference. Whether that's a bug depends on whether line items are meant to be shared references or parcel-specific editable data.
For parcel-specific copies, create each item object while constructing the draft, or map source items into a new representation. Don't assume "copying an array" also copies its elements. The same logic applies one level deeper: if an item includes a mutable options object, you still need to decide whether that options object should be shared or cloned.
The right depth depends on behavior. Share what is genuinely immutable or centrally owned. Create separate instances for state one parcel can change without affecting another.
How can you test draft isolation?
Test behavior, not just shape. A factory test that only asserts you got two entries mostly proves the array length. A useful test mutates one draft and verifies the other stays unchanged - including its nested objects and arrays.
Here's a complete Node.js example using node:assert/strict:
const assert = require('node:assert/strict');
function newParcelDrafts(count) {
if (!Number.isSafeInteger(count) || count < 0 || count > 100) {
throw new RangeError('Expected a draft count from 0 to 100');
}
return Array.from({ length: count }, (_, index) => ({
localSequence: index + 1,
weightGrams: null,
dimensionsCm: { length: null, width: null, height: null },
items: []
}));
}
const template = { dimensionsCm: { length: null }, items: [] };
const aliased = Array(2).fill(template);
aliased[0].dimensionsCm.length = 30;
assert.equal(aliased[1].dimensionsCm.length, 30);
const shallow = Array.from({ length: 2 }, () => ({ ...template }));
assert.notEqual(shallow[0], shallow[1]);
assert.equal(shallow[0].dimensionsCm, shallow[1].dimensionsCm);
assert.equal(shallow[0].items, shallow[1].items);
const drafts = newParcelDrafts(2);
assert.notEqual(drafts[0], drafts[1]);
assert.notEqual(drafts[0].dimensionsCm, drafts[1].dimensionsCm);
assert.notEqual(drafts[0].items, drafts[1].items);
drafts[0].weightGrams = 450;
drafts[0].dimensionsCm.length = 30;
drafts[0].items.push({ sku: 'EXAMPLE-A', quantity: 1 });
assert.equal(drafts[1].weightGrams, null);
assert.equal(drafts[1].dimensionsCm.length, null);
assert.deepEqual(drafts[1].items, []);
assert.deepEqual(drafts.map(p => p.localSequence), [1, 2]);
assert.deepEqual(newParcelDrafts(0), []);
assert.equal(newParcelDrafts(100).length, 100);
for (const invalid of [-1, 1.5, 101, '2', null, NaN, Infinity]) {
assert.throws(() => newParcelDrafts(invalid), RangeError);
}
const next = newParcelDrafts(1);
assert.notEqual(next[0].items, drafts[0].items);
assert.equal(next[0].dimensionsCm.length, null);
console.log('Independent parcel draft checks passed');
Save it as parcel-drafts.cjs and run it with Node.js. The first assertions deliberately confirm the shared-reference failure: mutating one entry affects the other. Then the shallow-spread assertions show why checking only outer-object identity isn't enough. Finally, the factory checks validate that changing one draft's weight, dimensions, and item list doesn't leak into its neighbor.
Test factory calls as well as entries
Isolation also has to hold across separate factory calls. A cached template or a module-level mutable array can make a later order inherit state from an earlier one. The example's last assertions create a fresh set and verify the nested data isn't reused.
This is a small test suite, but it hits several common failure modes that don't show up in "UI-only" checks. In a production adapter, add equivalent tests for every mutable nested field your request builder supports. If your schema changes, update the ownership tests alongside it.
What should a parcel-draft factory handle?
A factory should create predictable local state. It can validate the requested number of drafts is a safe input, build independent values, and assign an order-local sequence. It shouldn't quietly absorb logistics rules that belong somewhere else.
Keep limits and identifiers honest
The example's maximum of 100 drafts is just an illustrative safeguard. It isn't a carrier, warehouse, Shopify, or 3PL limit. Pick a real limit based on product requirements and whatever the receiving interface actually supports. If you don't have a real limit yet, state that explicitly instead of presenting an arbitrary number as an operational truth.
Also, localSequence is an index within this draft collection. It's not a parcel ID, shipping label number, tracking reference, or stable identifier across edits. If drafts are saved, reordered, or submitted asynchronously, the layer that owns persistence and shipment identity should maintain the real mapping between the order and its parcels.
That boundary keeps a small helper from turning into a misleading "integration abstraction." The factory should not validate that measurements are positive, confirm weights match carrier limits, allocate stock, split an order, or call a fulfillment API. Those concerns need their own rules and tests.
Agree on units and schema at the integration boundary
This sample uses grams and centimeters, but field names alone don't guarantee that an external system expects the same units. A cross-border fulfillment integration needs an agreed unit convention, the item schema, required fields, and how nulls are handled. A null value can be useful while a draft is incomplete - it may be invalid once you submit the request.
Before connecting to a real fulfillment interface, confirm how it represents parcel dimensions, weights, quantities, and product identifiers. Do conversion at a deliberate boundary, and test it with representative payloads. In US workflows, for example, a partner may expect inches and pounds; even in metric-first systems, you still want a clear contract rather than guessing based on geography.
If a project brief mentions a heading like "International Fulfillment for Folligen," treat it as hypothetical until the actual interface, account, and data contract are confirmed. A label in a brief doesn't establish a working connection - or a customer relationship with a particular 3PL.
The operational setup matters too. YX Fulfillment's Shopify setup guide, for example, lists the kinds of questions teams need to settle when configuring a Shopify fulfillment workflow. Your local adapter tests still matter: that setup guidance doesn't prove your payload shape, unit conversions, or order-to-parcel mapping are correct.
A useful review checklist before submission:
- Does each draft own every nested value that can be edited independently?
- Are units and required fields defined by the receiving interface?
- Are incomplete
nullvalues rejected or completed before submission? - Is the order-to-parcel mapping preserved when drafts are saved or sent?
- Are carrier rules, inventory allocation, and API calls handled outside this factory?
Conclusion
Two array entries aren't automatically two independent parcel drafts. fill() can repeat one object reference, and a shallow spread can leave nested objects and arrays shared. The reliable pattern is to create every mutable value at the level where it needs independent ownership, then test it by mutating one draft and checking that neighbors - and later factory results - stay unchanged.
Keep the factory narrow. Use it to create clean local state. Handle shipment identity, units, validation, inventory, and external requests where those responsibilities belong. Before wiring drafts into a fulfillment workflow, verify both the object graph and the integration contract. That simple discipline keeps a subtle reference bug from turning into incorrect parcel data.