JS Built-ins
← Array184 / 226
ArrayArray.prototype.spliceintermediate

Array.prototype.splice() β€” replace an element

πŸ“– Usage Example
const arr = ['a', 'b', 'c']
arr.splice(1, 1, 'X')  // β†’ ['b']  (removed)
arr  // β†’ ['a', 'X', 'c']

Use splice() to replace one or more elements at a position with new values.

Array.prototype.splice() β€” replacing

By passing 1 as deleteCount and a new value as the third argument, you can replace an element at any position in a single operation.

Challenge: Implement replaceAt(arr, index, val) that replaces the element at index with val and returns the mutated array.

replaceAt([1, 2, 3], 1, 99)  // β†’ [1, 99, 3]
replaceAt([10, 20, 30], 0, 5) // β†’ [5, 20, 30]
πŸ’‘ Hints (2)
  • β€’ `splice(index, 1, val)` removes 1 element and inserts `val` at the same position.
  • β€’ The array length does not change because you remove and insert exactly one element.