29

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?

Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
Bryce
  • 6,440
  • 8
  • 40
  • 64

7 Answers7

12

I understand the expectation for array.push() to return the mutated array instead of its new length. And the desire to use this syntax for chaining reasons.
However, there is a built in way to do this: array.concat(). Note that concat expects to be given an array, not an item. So, remember to wrap the item(s) you want to add in [], if they are not already in an array.

newArray = oldArray.concat([newItem]);

Array chaining can be accomplished by using .concat(), as it returns an array,
but not by .push(), as it returns an integer (the new length of the array).

Here is a common pattern used in React for changing the state variable, based on its prior value:

// the property value we are changing
selectedBook.shelf = newShelf;
       
this.setState((prevState) => (
  {books: prevState.books
           .filter((book) => (book.id !== selectedBook.id))
           .concat(selectedBook)
  }
));

state object has a books property, that holds an array of book.
book is an object with id, and shelf properties (among others).
setState() takes in an object that holds the new value to be assigned to state

selectedBook is already in the books array, but its property shelf needs to be changed.
We can only give setState a top level object, however.
We cannot tell it to go find the book, and look for a property on that book, and give it this new value.

So we take the books array as it were.
filter to remove the old copy of selectedBook.
Then concat to add selectedBook back in, after updating its shelf property.

Great use case for wanting to chain push.
However, the correct way to do this is actually with concat.

Summary:

  • array.push() returns a number (mutated array's new length).
  • array.concat([]) returns a new array.

Technically, it returns a new array with the modified element added to the end, and leaves the initial arrays unchanged. Returning a new array instance, as opposed to recycling the existing array instance is an important distinction, that makes it very useful for state objects in React applications, to get changed data to re-render.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
SherylHohman
  • 16,580
  • 17
  • 88
  • 94
  • Hmm, I don't understand. `oldArray.concat[newItem];` returns undefined for me in any normal JS environment. There's an interesting related discussion at https://2ality.com/2016/11/concat-array-literal.html, but no explanation of how your syntax can be expected to work. I assume this is a React-specific thing? Some magic messing with the array prototype? – Tao Sep 06 '19 at 08:03
  • 1
    I think you have a typo @Tao. It should be `oldArray.concat(newItem)` – Nick Manning Nov 25 '20 at 21:43
  • 3
    Thanks @NickManning, that was indeed the point; about 5 months after my comment, @SherylHohman edited the answer to change the apparently-wrong `newArray = oldArray.concat[newItem];` to the corrected `newArray = oldArray.concat([newItem]);`, thereby answering my question. They did leave the wrong syntax in the summary at the bottom, however, which I have now also corrected. My confusion is fully addressed. – Tao Nov 26 '20 at 06:34
  • 2
    Yeah - for the record I think you can concat an item too [].concat(3) and [].concat([3]) both do the same thing. – Nick Manning Nov 26 '20 at 20:21
12

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 original jsarray.c source

/*
 * If JS1.2, follow Perl4 by returning the last thing pushed.  Otherwise,
 * return the new array length.
 */
romellem
  • 5,792
  • 1
  • 32
  • 64
2

I cannot explain why they chose to return the new length, but in response to your suggestions:

  • Returning the newly appended item:

Given that JavaScript uses C-style assignment which emits the assigned value (as opposed to Basic-style assignment which does not) you can still have that behavior:

var addedItem;
myArray.push( addedItem = someExpression() );

(though I recognise this does mean you can't have it as part of an r-value in a declaration+assignment combination)

  • Returning the mutated array itself:

That would be in the style of "fluent" APIs which gained popularity significantly after ECMAScript 3 was completed and it would not be keeping in the style of other library features in ECMAScript, and again, it isn't that much extra legwork to enable the scenarios you're after by creating your own push method:

Array.prototype.push2 = function(x) {
    this.push(x);
    return this;
};

myArray.push2( foo ).push2( bar ).push2( baz );

or:

Array.prototype.push3 = function(x) {
    this.push(x);
    return x;
};

var foo = myArray.push3( computeFoo() );
Dai
  • 141,631
  • 28
  • 261
  • 374
  • 2
    Re fluent APIs: None of the methods that mutate an array do return that array. They're not really supposed to be chainable if you use them mostly for side effects. – Bergi Dec 14 '15 at 04:06
2

I was curious since you asked. I made a sample array and inspected it in Chrome.

var arr = [];
arr.push(1);
arr.push(2);
arr.push(3);
console.log(arr);

enter image description here

Since I already have reference to the array as well as every object I push into it, there's only one other property that could be useful... length. By returning this one additional value of the Array data structure, I now have access to all the relevant information. It seems like the best design choice. That, or return nothing at all if you want to argue for the sake of saving 1 single machine instruction.

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

No clue - I'm not certain a record of rationale along these lines exists. It would be up to the implementer and is likely commented in any given code base implementing the ECMA script standards.

ThisClark
  • 14,352
  • 10
  • 69
  • 100
  • 1
    [1,2,3].map(x => x+=4).push(1) //=== 4, it would be really nice if it returns [5,6,7,1], wouldn't? But... [1,2,3].map(x => x+=4).concat(1) //=== [5, 6, 7, 1] – MrHIDEn Jul 10 '18 at 08:17
1

If you are "chaining" operations together, and it is useful to obtain a reference to the array you have just pushed an item into, you can use a comma expression:

const a = [1,2,3]
const b = (a.push(4), a).reverse()
console.log(a)
console.log(b)

If you want to create a new array with an extra element added, you can use spread syntax:

const a = [1,2,3]
const b = [...a, 4].reverse()
console.log(a)
console.log(b)

Note that reverse() reverses an array in place. This is why in the first example, both a and b variables reference the same reversed array. In the second example, a and b reference different arrays, only one of which has been reversed.

Andrew Parks
  • 6,358
  • 2
  • 12
  • 27
0

I don't know "Why was it done like this, and is there a historical record of how these decisions came to be made?".

But I also think it's not clear and not intuitive that push() returns the length of array like below:

let arr = ["a", "b"];

let test = arr.push("c");

console.log(test); // 3

Then, if you want to use clear and intuitive method instead of push(), you can use concat() which returns the array with its values like below:

let arr = ["a", "b"];

let test = arr.concat("c");

console.log(test); // ["a", "b", "c"]
Super Kai - Kazuya Ito
  • 22,221
  • 10
  • 124
  • 129
0

The question is partially answered in the document you mention (Ecma 262 3rd edition), there are methods that mutate the array and methods that don't. The methods that mutate the array will return the length of the mutated array. For adding elements that would be push, splice and unshift (Depending on the position you want the new element in).

If you want to get the new mutated array you can use concat. Concat will input any number of arrays you want added to the original array and add all the elements into a new array. i.e:

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3=['g','h'];
const array4 = array1.concat(array2,array3);

The new array created will have all the elements and the other three won't be changed. There are other (Many) ways to add the elements to an array both mutative and not mutative. So there is your answer, it returns the length because it is changing it, it doesn't need to return the full array.