How do you replace an item at a specific index in a JavaScript array? | A1Lab@FahadM to JavaScriptEnglish • 4 days ago

How do you replace an item at a specific index in a JavaScript array?

message-square
0

To replace an item at a specific index in a JavaScript array without mutating the original array, use Array.prototype.with(index, newValue) (ES2023+) or arr.map((item, idx) => (idx === targetIndex ? newValue : item)) after validating that index is a valid integer within [0, arr.length - 1]. When you intentionally want to mutate a local array in place, assign arr[index] = newValue or call arr.splice(index, 1, newValue) after checking bounds.


1. Non-Mutating Replacement with .with() / .map() and Bounds Guards

Validate that items is an array and index is a valid integer in bounds (0 <= index < items.length), then return a brand-new array with only the target slot replaced while leaving the original array untouched:

// Replace an item at a specific index without mutating the source array
function replaceAtIndexImmutable(items, index, nextValue) {
  if (!Array.isArray(items)) {
    throw new TypeError("Expected items to be an Array.");
  }

  if (!Number.isInteger(index) || index < 0 || index >= items.length) {
    throw new RangeError(
      `Index ${String(index)} is out of bounds for array of length ${items.length}.`
    );
  }

  if (typeof items.with === "function") {
    return items.with(index, nextValue);
  }

  return items.map((currentItem, idx) => (idx === index ? nextValue : currentItem));
}

// Example usage:
const steps = Object.freeze(["fetch", "parse", "render"]);
const updatedSteps = replaceAtIndexImmutable(steps, 1, "validate");
console.log(updatedSteps); // ["fetch", "validate", "render"]
console.log(steps);        // ["fetch", "parse", "render"]
  • Safe for frozen & shared arrays: Returns a new array without mutating steps or breaking state/props in UI frameworks.
  • Strict integer & bounds checks: Rejects negative numbers, floating-point indices, or out-of-range indices explicitly instead of silently creating sparse holes.

2. In-Place Replacement When Mutation Is Intended (arr[index] or .splice())

When working with a local mutable array where in-place mutation is desired, validate the index bounds first and update targetArray[index] = nextValue (or targetArray.splice(index, 1, nextValue)):

// Replace an item in place on a mutable array after checking bounds
function replaceAtIndexInPlace(targetArray, index, nextValue) {
  if (!Array.isArray(targetArray)) {
    throw new TypeError("Expected targetArray to be an Array.");
  }

  if (Object.isFrozen(targetArray)) {
    throw new TypeError("Cannot mutate a frozen array.");
  }

  if (!Number.isInteger(index) || index < 0 || index >= targetArray.length) {
    throw new RangeError(
      `Index ${String(index)} is out of bounds for array of length ${targetArray.length}.`
    );
  }

  targetArray[index] = nextValue;
  return targetArray;
}

// Example usage:
const scores = [10, 20, 30];
replaceAtIndexInPlace(scores, 0, 15);
console.log(scores); // [15, 20, 30]
  • Direct slot assignment: targetArray[index] = nextValue replaces a single element in O(1) time without shifting surrounding elements.
  • Explicit error on invalid index: Throws RangeError rather than silently writing past length - 1.

3. Common Traps to Avoid

Replacing an item at a specific index in a JavaScript array often runs into a few pitfalls:

  • Assigning to a negative or out-of-bounds index (arr[-1] = x or arr[10] = x): Unlike Python lists, arr[-1] in JavaScript creates a string property named "-1" on the array object rather than indexing from the end, and arr[10] on a 3-element array creates empty sparse slots.
  • Mutating shared arrays in place by accident: Using arr[i] = val or arr.splice(i, 1, val) on a shared array mutates every reference pointing to that array.
  • Forgetting Number.isInteger(index): Passing "1" or 1.5 can behave unexpectedly if not validated as an integer index first.

TL;DR: Guard Number.isInteger(index) && index >= 0 && index < arr.length and use arr.with(index, val) or .map((item, i) => (i === index ? val : item)) to replace an item immutably, or arr[index] = val when intentional in-place mutation is safe.