Tags
Asked 3 years ago
9 Jun 2021
Views 362
eclipse-learner

eclipse-learner posted

Difference between push and assignment in JavaScript array

Difference between push and assignment in JavaScript array
sarah

sarah
answered Apr 26 '23 00:00

In JavaScript, you can insert an item into an array at a specific index using the splice() method. Here's an example:



const myArray = ['apple', 'banana', 'orange'];

// Insert a new item 'grape' at index 1
myArray.splice(1, 0, 'grape');

// Output the updated array
console.log(myArray); // ['apple', 'grape', 'banana', 'orange']
In this example, we have an array myArray containing three items. To insert a new item 'grape' at index 1 (i.e., between 'apple' and 'banana'), we use the splice() method with the following parameters:


The first parameter is the index where the insertion should start (1 in this case).
The second parameter is the number of items to remove (0 in this case, since we're not removing any items).
The third parameter is the item to insert ('grape' in this case).
After calling splice(), the array myArray will contain the updated items 'apple', 'grape', 'banana', and 'orange'.

Note that splice() modifies the original array in place, so there's no need to assign the result back to the original variable. Also note that the first parameter (the index) can be negative, in which case the insertion starts from the end of the array.







equivalent to push() or pop() for arrays?
In JavaScript, arrays have several built-in methods that are equivalent to push() and pop():


push(): adds one or more elements to the end of an array and returns the new length of the array.
javascript
Copy code
const arr = [1, 2, 3];
arr.push(4, 5);
console.log(arr); // [1, 2, 3, 4, 5]
Post Answer