Ever since its introduction in ECMA-262, 3rd Edition, the Array.prototype.push
method's return value is a Number
:
15.4.4.7 Array.prototype.push ( [ item1 [ , item2 [ , … ] ] ] )
The arguments are appended to the end of the array, in the order in which they appear. The new length of the array is returned as the result of the call.
What were the design decisions behind returning the array's new length, as opposed to returning something potentially more useful, like:
Why was it done like this, and is there a historical record of how these decisions came to be made?
JavaScript Array push() The push() method adds new items to the end of an array. The push() method changes the length of the array. The push() method returns the new length.
The JavaScript array prototype constructor is used to allow to add new methods and properties to the Array() object. If the method is constructed, then it will available for every array. When constructing a property, All arrays will be given the property, and its value, as default.
To push an object into an array, call the push() method, passing it the object as a parameter. For example, arr. push({name: 'Tom'}) pushes the object into the array. The push method adds one or more elements to the end of the array.
The arr. push() method is used to push one or more values into the array. This method changes the length of the array by the number of elements added to the array. Parameters This method contains as many numbers of parameters as the number of elements to be inserted into the array.
I posted this in TC39's communication hub, and was able to learn a bit more about the history behind this:
push
,pop
,shift
,unshift
were originally added to JS1.2 (Netscape 4) in 1997.There were modeled after the similarly named functions in Perl.
JS1.2 push followed the Perl 4 convention of returning the last item pushed. In JS1.3 (Netscape 4.06 summer 1998) changed push to follow the Perl 5 conventions of returning the new length of the array.
see https://dxr.mozilla.org/classic/source/js/src/jsarray.c#804
/* * If JS1.2, follow Perl4 by returning the last thing pushed. Otherwise, * return the new array length. */
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With