JavaScript(JS) JS insert item in an array

To insert an item into an array in JavaScript, you can use the splice() method. The splice() method allows you to add and/or remove elements from an array.

The basic syntax for using splice() to insert an item into an array is as follows:

refer ‮gi:ot‬iftidea.com
array.splice(index, 0, item);
  • array: the array to modify
  • index: the index where the item should be inserted
  • 0: the number of items to remove from the array (in this case, zero)
  • item: the item to insert

Here's an example of how to use splice() to insert an item into an array:

let fruits = ["apple", "banana", "orange"];
fruits.splice(1, 0, "grape");
console.log(fruits); // ["apple", "grape", "banana", "orange"]

In this example, the splice() method is called on the fruits array with the arguments (1, 0, "grape"). This inserts the string "grape" into the fruits array at index 1, without removing any elements. The resulting fruits array is ["apple", "grape", "banana", "orange"].