To extend an existing JavaScript array in place with another array, validate that both arguments are Array instances (Array.isArray(targetArray) and Array.isArray(sourceItems)), mutate targetArray directly using targetArray.push(...sourceItems) for normal-sized arrays (or chunked push / for...of loops when sourceItems may be very large) inside a try / catch block—rather than reassigning targetArray = targetArray.concat(sourceItems) or [...targetArray, ...sourceItems], which creates a new array instead of mutating the original reference in place.
1. Extending an Array in Place with Array.prototype.push(...items) and Chunking
Use push(...sourceItems) to append elements directly onto targetArray while preserving external references to the same array instance, and fall back to chunked push when sourceItems.length is large so argument-list limits are never exceeded:
// Extend targetArray in place with elements from sourceItems safely
function extendArrayInPlace(targetArray, sourceItems, { chunkSize = 10000 } = {}) {
if (!Array.isArray(targetArray)) {
throw new TypeError("Expected targetArray to be an Array instance.");
}
if (!Array.isArray(sourceItems)) {
throw new TypeError("Expected sourceItems to be an Array instance.");
}
if (typeof chunkSize !== "number" || !Number.isInteger(chunkSize) || chunkSize < 1) {
throw new RangeError("Expected chunkSize to be a positive integer.");
}
try {
if (sourceItems.length === 0) {
return targetArray;
}
if (sourceItems.length <= chunkSize) {
targetArray.push(...sourceItems);
return targetArray;
}
for (let startIndex = 0; startIndex < sourceItems.length; startIndex += chunkSize) {
const sliceChunk = sourceItems.slice(startIndex, startIndex + chunkSize);
targetArray.push(...sliceChunk);
}
return targetArray;
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed extending array in place: ${message}`);
}
}
// Example usage:
// try {
// const queue = ["task-1", "task-2"];
// const queueRef = queue;
// extendArrayInPlace(queue, ["task-3", "task-4"]);
// console.log("Mutated in place:", queue === queueRef, queue); // true, ["task-1", "task-2", "task-3", "task-4"]
// } catch (error) {
// console.error(`${error.name}:${error.message}`);
// }
.push(...items)mutates the existing array and returns the new.length: Any variable or closure holding a reference totargetArrayimmediately sees the appended elements.- Avoid
.concat()or[...a, ...b]when in-place mutation is required: Both return a brand-new array and leave the original array unchanged unless reassigned.
2. Tracking In-Place Extensions Across Named Collections with a Map
When managing multiple target arrays or recording how many items were appended per batch key, store array references and batch metadata in a Map so dynamic keys never collide with Object.prototype properties:
// Append items to a named array stored in a Map and track extension counts
function appendBatchToNamedArray(collectionsMap, collectionKey, incomingItems) {
if (!(collectionsMap instanceof Map)) {
throw new TypeError("Expected collectionsMap to be a Map instance.");
}
if (typeof collectionKey !== "string" || collectionKey.trim().length === 0) {
throw new TypeError("Expected collectionKey to be a non-empty string.");
}
if (!Array.isArray(incomingItems)) {
throw new TypeError("Expected incomingItems to be an Array instance.");
}
try {
const cleanKey = collectionKey.trim();
const existingArray = collectionsMap.get(cleanKey);
if (!Array.isArray(existingArray)) {
throw new Error(`No Array found in collectionsMap under key "${cleanKey}".`);
}
const previousLength = existingArray.length;
extendArrayInPlace(existingArray, incomingItems);
return {
key: cleanKey,
previousLength,
currentLength: existingArray.length,
appendedCount: existingArray.length - previousLength
};
} catch (error) {
const message = error instanceof Error ? error.message : String(error);
throw new Error(`Failed appending batch to "${collectionKey}": ${message}`);
}
}
// Example usage:
// try {
// const logs = ["init"];
// const registry = new Map([["auditLogs", logs]]);
// const summary = appendBatchToNamedArray(registry, "auditLogs", ["login", "export"]);
// console.log("Appended:", summary.appendedCount, "Same ref:", registry.get("auditLogs") === logs);
// } catch (error) {
// console.error(`${error.name}:${error.message}`);
// }
- Use
Mapfor named collections: Prevents prototype collisions (constructor,toString,hasOwnProperty) when keys come from external or dynamic sources. - Validate
Array.isArray(...)rather thantypeof:typeof []is"object", whereasArray.isArray(...)reliably verifies true arrays (including across realms/iframes).
3. Argument-Spread Limits, Self-Extension, and Mutation Caveats
Keep these array mutation details in mind when extending arrays in place:
- Spreading huge arrays (
push(...hugeArray)) can hit call-stack / argument limits: Chunking large arrays avoids passing tens of thousands of arguments at once. - Extending an array with itself (
extendArrayInPlace(arr, arr)) can loop infinitely if iterating overarr.lengthdynamically: Passing a separatesourceItemsarray or slicing a snapshot avoids self-growth loops. - In-place mutation affects shared references and React state: In React, mutating state arrays in place does not trigger a re-render unless a new array reference is passed to
setState; use in-place.push()for mutable buffers/queues or non-state collections.
