DEV Community

Shameel Uddin
Shameel Uddin

Posted on

Introducing a Better Way to Replace Array Values in JavaScript! ๐Ÿš€

I have been using splice method to replace array values but recently learned a newer way for this purpose, thus sharing it with the rest.

Out with the Old ๐Ÿ•ฐ๏ธ - Splice Method

Let's take a look at the newer way of replacing values in an array using the splice method:

const initialFruits = ["๐ŸŽ", "๐ŸŒ", "๐Ÿ‡", "๐ŸŠ", "๐Ÿ“"];
const newFruits = [...initialFruits];
newFruits.splice(3, 1, "๐Ÿ");
console.log(initialFruits);
// ["๐ŸŽ", "๐ŸŒ", "๐Ÿ‡", "๐ŸŠ", "๐Ÿ“"]
console.log(newFruits);
// ["๐ŸŽ", "๐ŸŒ", "๐Ÿ‡", "๐Ÿ", "๐Ÿ“"]
Enter fullscreen mode Exit fullscreen mode

Not only is this approach cumbersome, but it also lacks the clarity we crave in modern JavaScript development. ๐Ÿ˜ฉ

In with the New ๐Ÿ†• - With Method

Now, Let's take a look at the traditional way of replacing values in an array using the with method:

const initialFruits = ["๐ŸŽ", "๐ŸŒ", "๐Ÿ‡", "๐ŸŠ", "๐Ÿ“"];
const newFruits = initialFruits.with(3, "๐Ÿ");
console.log(initialFruits);
// ["๐ŸŽ", "๐ŸŒ", "๐Ÿ‡", "๐ŸŠ", "๐Ÿ“"]
console.log(newFruits);
// ["๐ŸŽ", "๐ŸŒ", "๐Ÿ‡", "๐Ÿ", "๐Ÿ“"]

Enter fullscreen mode Exit fullscreen mode

I found this method much more clearer than the older one. Let me know your thoughts. =)

Happy coding! ๐ŸŽ‰๐Ÿ’ปโœจ

Follow me for more such content:
LinkedIn: https://www.linkedin.com/in/shameeluddin/
Github: https://github.com/Shameel123

Top comments (3)

Collapse
 
michaeltharrington profile image
Michael Tharrington

Nice on, Shameel! ๐Ÿ”ฅ

Collapse
 
shameel profile image
Shameel Uddin

Thanks! =D

Collapse
 
lionelrowe profile image
lionel-rowe • Edited

Not only is this approach cumbersome, but it also lacks the clarity we crave in modern JavaScript development. ๐Ÿ˜ฉ

It's true the API is a little cumbersome (often you want to either remove elements or add them, not do both in the same operation), but the main issue with it is in-place mutation. Sometimes that can be useful, but more often than not you want a copy of the array instead.

Array#with isn't a drop-in immutable replacement for Array#splice; it only covers the Array#splice(existingIndex, 1, singleReplacement) case. It's a much better API for that use case, but not as versatile as Array#splice.

There is now a drop-in immutable replacement though, which is called Array#toSpliced. It has an identical API to Array#splice, except it doesn't mutate the original array and returns the copied array with modifications.