Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Array.prototype.push return the new length instead of something more useful?

Tags:

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:

  • A reference to the newly appended item/s
  • The mutated array itself

Why was it done like this, and is there a historical record of how these decisions came to be made?

like image 829
Bryce Avatar asked Dec 14 '15 03:12

Bryce


People also ask

Does array push return new array?

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.

What does array prototype do?

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.

How do you push data into an array of objects?

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.

How do you push an array into an 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.


1 Answers

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.  */ 
like image 93
romellem Avatar answered Nov 09 '22 09:11

romellem