Home >Web Front-end >JS Tutorial >Why Does Array.prototype.Push Return the New Array Length?
Why Does Array.prototype.push Return the New Array Length?
In JavaScript, the Array.prototype.push method conveniently allows appending elements to the end of an array. However, its peculiarity lies in returning the new array length instead of something seemingly more valuable.
This decision dates back to the inception of push in JavaScript 1.2 in 1997. Inspired by Perl's array manipulation functions, JS1.2 push initially returned the last item pushed, adhering to Perl 4 conventions.
As JavaScript evolved to JS1.3, a significant change occurred. The push function was modified to follow the Perl 5 convention, which dictated returning the new array length. This decision can be traced back to the original jsarray.c source code, where it was noted that, in the event of JavaScript 1.2, the function should return the last item pushed, while for other versions, it should return the new length.
It's worth noting that this seemingly inconsequential choice has significant implications. By returning the new length, push enables easy chainability, allowing subsequent operations to be performed on the modified array without having to re-assign it. For instance, one could concatenate arrays and sort them all in a single line of code:
const result = [1, 2].push(3).push(4).sort(); console.log(result); // Output: [1, 2, 3, 4]
Moreover, returning the new length provides a consistent interface across all array manipulation methods, such as pop and shift, which also return the changed length rather than the removed element. This uniformity simplifies usage and reduces cognitive overhead for developers.
The above is the detailed content of Why Does Array.prototype.Push Return the New Array Length?. For more information, please follow other related articles on the PHP Chinese website!