Friday 18 January 2019

Does it mutate?

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 to ArticlePermalink

The post Does it mutate? appeared first on CSS-Tricks.



from CSS-Tricks http://bit.ly/2QUuYbm
via IFTTT

No comments:

Post a Comment

Passkeys: What the Heck and Why?

These things called  passkeys  sure are making the rounds these days. They were a main attraction at  W3C TPAC 2022 , gained support in  Saf...