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

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

πŸ“– Usage Example
const arr = [1, 2, 4, 5]
arr.splice(2, 0, 3)  // insert 3 at index 2
arr  // β†’ [1, 2, 3, 4, 5]

Pass 0 as deleteCount and provide values to splice() to insert elements without removing any.

Array.prototype.splice() β€” inserting

Passing 0 as the deleteCount tells splice to delete nothing and only insert elements at the given position.

Challenge: Implement insertAt(arr, index, val) that inserts val at index (shifting existing elements right) and returns the mutated array.

insertAt([1, 2, 3], 1, 99) // β†’ [1, 99, 2, 3]
insertAt([10, 20], 0, 5)   // β†’ [5, 10, 20]
πŸ’‘ Hints (2)
  • β€’ `splice(index, 0, val)` β€” deleting 0 elements means only insertion happens.
  • β€’ Elements at `index` and beyond are shifted one position to the right.