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
Great resource – I always find myself trolling around on the MDN Array reference to see what Arrays can do natively.
Just a quick note –
arr.slice(-1)
will result in["mee"]
, not"mee"