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

Shameel Uddin - Dec 6 '23 - - Dev Community

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

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player