DEV Community

Discussion on: Be Careful with Array Mutators

Collapse
 
lukaszwiktor profile image
Łukasz Wiktor

Can you give an example of a hard-to-find bug caused by array.sort()?

Collapse
 
emiloberg profile image
Emil Öberg

// utils.js
export function getTop(list) {
return list
.sort()
.slice(0, 1)
}

// some-other-file.js
import { getTop } from “./utils”

const movies = getMoviesFromDb()
const topMovie = getTop(movies)

// movies is now not what you think it would be.

Collapse
 
cartant profile image
Nicholas Jamieson

The example that Emil gave is pretty typical.

I've seen the bug introduced in a Redux selector that did something similar - it sorted the array using some criteria and returned the top 10 or so elements.

In doing so, the selector mutated the Redux store - something that should never happen. The bug was 'hard-to-find' because:

  • the bug was only effected if the app functionality that exercised the selector was used;
  • whether or not the bug was effected depended upon the data in the store and how 'sorted' it was; and
  • when it was effected, parts of the app seemed to be weirdly inconsistent.