Why is Array.prototype.push returning a new length instead of something more useful?

Since its introduction in ECMA-262, 3rd edition , the return value of a method Array.prototype.pushis Number:

15.4.4.7 Array.prototype.push ([item1 [, item2 [, ...]]])

Arguments are added to the end of the array in the order they appear. The new length of the array is returned as the result of the call.

What were the constructive solutions for returning an array of new length, as opposed to returning something potentially more useful, for example:

  • Link to recently added item (s)
  • Mutated array itself

Why was this done so, and is there a historical account of how these decisions were made?

+8
4

, , :

  • :

, JavaScript C, ( , ), :

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

( , , r + )

  • :

"" API, ECMAScript 3, ECMAScript, , , , push:

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

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

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

var foo = myArray.push3( computeFoo() );
+2

, . Chrome.

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

enter image description here

, , , , ... length. Array, . . , .

, , ?

- , . , , , ECMA script.

+2

, array.push() . .
: array.concat[]

newArray = oldArray.concat[newItem];

.concat[] .push().

, React state :

// the property value we are changing
selectedBook.shelf = newShelf;

this.setState((prevState) => (
  {books: prevState.books
           .filter((book) => (book.id !== selectedBook.id))
           .concat(selectedBook)
  }
));

state books, book.
book - id shelf ( ).
setState() , state

selectedBook books, shelf .
setState .
, , .

, books .
filter, selectedBook.
concat selectedBook , shelf.

push.
concat.

: array.push() ( ).
array.concat[] .

+2

TC39 :

push, pop, shift, unshift JS1.2 (Netscape 4) 1997 .

Perl.

JS1.2 push Perl 4 . JS1.3 (Netscape 4.06, 1998) push, Perl 5 .

. 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.
 */
0

Source: https://habr.com/ru/post/1538513/


All Articles