Tags
Asked 3 years ago
9 Jun 2021
Views 452
angeo

angeo posted

Array.push return pushed value

Array.push return pushed value?
david

david
answered Apr 27 '23 00:00

In JavaScript, the Array.push() method does not return the pushed value, but instead returns the new length of the array after the push operation.

Here is an example:




const myArray = [1, 2, 3];
const newLength = myArray.push(4);


console.log(newLength); // Output: 4
console.log(myArray);   // Output: [1, 2, 3, 4]

In this example, we have an array myArray with three elements. We call the push() method on the array to add the value 4 to the end of the array. The push () method returns the new length of the array, which is 4 , and this value is assigned to the variable newLength.

If you want to retrieve the pushed value, you can do so by accessing the last element of the array using the index myArray[myArray.length - 1] or using the Array.slice() method:


c

onst myArray = [1, 2, 3];
const pushedValue = myArray.push(4) && myArray.slice(-1)[0];

console.log(pushedValue); // Output: 4
console.log(myArray);     // Output: [1, 2, 3, 4]

In this example, we assign the pushed value to the variable pushedValue using the Array.slice() method to extract the last element of the array. Note that we also use the && operator to make sure that the push() method is executed before calling slice() on the array.
Post Answer