Does it mutate?

Avatar of Chris Coyier
Chris Coyier on

UGURUS offers elite coaching and mentorship for agency owners looking to grow. Start with the free Agency Accelerator today.

This little site by Remy Sharp’s makes it clear whether or not a JavaScript method changes the original array (aka mutates) or not.

I was actually bitten by this the other day. I needed the last element from an array, so I remembered .pop() and used it.

const arr = ["doe", "ray", "mee"];
const last = arr.pop();
// mee, but array is now ["doe", "ray"]

This certainly worked great right away, but I didn’t realize the original array had changed and it caused a problem. Instead, I had to find the non-mutating alternative:

const arr = ["doe", "ray", "mee"];
const last = arr.slice(-1);
// ["mee"], arr is unchanged

Related: Array Explorer

Direct Link →