Home >Web Front-end >JS Tutorial >What Motivated the Return Value Choice of Array.prototype.push?
Understanding Array.prototype.push's Return Value: A Historical Perspective
The Array.prototype.push method in JavaScript has consistently returned the new length of the array since its introduction. This design choice has sparked curiosity among developers, who speculate that it could have been more useful to return other data.
Return Value Options
Instead of the array's new length, the push method could have potentially returned:
Rationale Behind the Length Return
The decision to return the array's new length stems from the influence of Perl's array manipulation functions. In Perl 4, the push function returned the last pushed item. However, in Perl 5, the convention was changed to return the new array length. JavaScript's push method in its early iterations (JS1.2) followed the Perl 4 convention.
In JS1.3, push was modified to align with Perl 5's behavior, returning the new array length. The rationale behind this change was likely to provide a consistent experience across different versions of JavaScript and Perl.
Historical Record
A review of the early JavaScript source code in jsarray.c reveals the following:
/* * If JS1.2, follow Perl4 by returning the last thing pushed. Otherwise, * return the new array length. */
This snippet suggests that the shift from returning the last item pushed to the new array length was a deliberate change made in JS1.3.
Implications
The current behavior of push returning the array's new length has become an integral part of JavaScript programming. This allows developers to easily chain push operations, ensuring that the array's length is always available.
The above is the detailed content of What Motivated the Return Value Choice of Array.prototype.push?. For more information, please follow other related articles on the PHP Chinese website!