DEV Community

Cover image for 👨‍💻 Splice method in JavaScript : Unveiling the Magic of JavaScript Arrays
Manikandan K
Manikandan K

Posted on

👨‍💻 Splice method in JavaScript : Unveiling the Magic of JavaScript Arrays

In the vast landscape of JavaScript, arrays reign supreme as indispensable tools for data manipulation. Among the myriad methods available for array manipulation, one stands out as the cornerstone of versatility and power: the splice() method. In this article, we embark on a journey to uncover the secrets and nuances of this exceptional method, exploring its ability to create, delete, and update elements within arrays.

What is splice()?

  • The splice() method adds and/or removes array elements.
  • The splice() method overwrites the original array.

syntax
array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, item1)
array.splice(start, deleteCount, item1, item2)
array.splice(start, deleteCount, item1, item2, ...itemN)

Creating, Deleting, and Updating with Ease

  • Whether you want to add something new, remove the old, or update what's already there, splice() has got you covered.

Adding Elements

  • Say you have an array of names and you want to add a new one to it. With splice(), you can do that without breaking a sweat.

Image description

Updating Elements

  • Sometimes you just need to freshen things up a bit. With splice(), you can easily swap out old data for new, keeping your array looking sharp.

Image description

Deleting Elements

  • Maybe you've got too many items in your array, or some of them are just no longer needed. splice() can help you get rid of them in a snap.

Image description

Insert element

Image description

Source code:

const name = ['Manikandan', 'Aradvind', 'Kathiresan', 'Susila'];
console.log(name) 
// [ 'Manikandan', 'Aradvind', 'Kathiresan', 'Susila' ]


// CREATE
name.splice(name.length, 1, "Vignesh");
console.log(name) 
// [ 'Manikandan', 'Aradvind', 'Kathiresan', 'Susila', 'Vignesh' ]

// UPDATE
name.splice(1, 1, "Aravind");
console.log(name)
// [ 'Manikandan', 'Aravind', 'Kathiresan', 'Susila', 'Vignesh' ]


// DELETE
name.splice(0,1);
console.log(name)
// [ 'Aradvind', 'Kathiresan', 'Susila', 'Vignesh' ]



// INSERT INBETWEEN
name.splice(3, 0, "Siva");
console.log(name)
// [ 'Aradvind', 'Kathiresan', 'Susila', 'Siva', 'Vignesh' ]


// INSERT START
name.splice(0, 0, "Aswin");
console.log(name)
// [ 'Aswin', 'Aradvind', 'Kathiresan', 'Susila', 'Siva', 'Vignesh' ]

Enter fullscreen mode Exit fullscreen mode

Conclusion

When it comes to working with arrays in JavaScript, splice() is the method you'll want to have in your toolkit. Its ability to create, delete, and update elements makes it a true powerhouse for data manipulation. So next time you find yourself wrangling with arrays, remember the magic of splice() and let it work its wonders for you.

Top comments (0)