Home > Web Front-end > JS Tutorial > body text

Why Does Array.prototype.Push Return the New Array Length?

Patricia Arquette
Release: 2024-10-22 11:54:02
Original
537 people have browsed it

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]
Copy after login

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!

source:php
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!