In JavaScript, How Can An Item Be Inserted Into An Array At A Particular Index?

To insert an item into an array at a specific index in JavaScript, you can use the splice() method. Here’s an example:

// Sample array
let array = ["banana", "apple", "orange"];

// Index at which the item needs to be inserted
let index = 1;

// Item to be inserted
let item = "pear";

// Using splice() to insert the item at the specific index
array.splice(index, 0, item);



["banana", "pear", "apple", "orange"]

In the splice() method, the first parameter is the index at which the insertion should happen, the second parameter specifies the number of elements to be removed (in this case, 0), and the third parameter is the item to be inserted.

About the Author Rex

I'm a passionate tech blogger with an insatiable love for programming! From my early days tinkering with code, I've delved into web dev, mobile apps, and AI. Sharing insights and tutorials with the world is my joy, connecting me to a global community of like-minded tech enthusiasts. Python holds a special place in my heart, but I embrace all challenges. Constantly learning, I attend tech conferences, contribute to open-source projects, and engage in code review sessions. My ultimate goal is to inspire the next generation of developers and contribute positively to the ever-evolving tech landscape. Let's code together!