ajamil
answered Apr 27 '23 00:00
The Array.prototype.push() method in JavaScript is designed to add one or more elements to the end of an array and return the new length of the array. This behavior is consistent with other array methods in JavaScript, such as Array.prototype.pop() and Array.prototype.unshift( ), which also return a value that represents the new length of the array after the operation is performed.
The reason for returning the new length instead of the modified array itself is to allow for method chaining. Method chaining is a programming pattern where multiple methods are called on an object in a single statement, with the output of one method being used as the input for the next method. This pattern is often used in JavaScript to write more concise and readable code.
For example, if we have an array myArray and we want to add multiple elements to it and then perform some operation on the resulting array, we can use method chaining like this:
const newArrayLength = myArray.push(4, 5, 6).sort().reverse().length;
In this example, we first add elements 4, 5, and 6 to the end of the myArray using the push () method. Then, we sort the array using the sort() method, reverse the order of the elements using the reverse() method, and finally, we get the new length of the array using the length property.
If the push() method were to return the modified array instead of the new length, this method chaining would not be possible, or it would be more cumbersome to write. Therefore, returning the new length allows for more flexible and readable code in JavaScript.