Yesterday, I came across an interesting bug regarding JavaScript Arrays, and I wanted to share my approach to fixing it.

At a basic level, I wanted to pass part of an array to a function, but wanted to use the original array later on.

let arr = [1, 2, 3, 4, 5]

let something = arr.splice(0, 3)

do(something) // []

DoSomethingWithOriginal(arr)

Thinking that Array.prototype functions don’t mutate the array directly, I moved on with my day. This lead to a bunch of problems down the line.

Some array methods in the EcmaScript specification are designed to mutate arrays, while others do not.

Non-mutating functions

Array.prototype.map()

Array.prototype.slice()

Array.prototype.join()

…

These functions do not mutate the array they are called on. For example:

let arr = [1, 2, 3, 4, 5]

let partOfArr = arr.slice(1, 2)

console.log(partOfArr) // [2, 3]

console.log(arr) // [1, 2, 3, 4, 5]

Mutating functions

Array.prototype.sort()

Array.prototype.splice()

Array.prototype.reverse()

…

These methods mutate the array directly. This can lead to unreadable code, as the value can be manipulated from anywhere. For example: