jskatas.org Continuously Learn JavaScript. Your Way.

Array API: array.push() (as introduced in ES3)

The push() function adds one or more elements to the end of an array.

array.push()

passing zero or one argument

GIVEN an empty array WHEN pushing nothing to it THEN the array stays empty
const arr = []; arr.push(42); assert.deepEqual(arr, []);
GIVEN an array with one item WHEN pushing nothing to it THEN the call return 1, the length of the array
const arr = []; assert.deepEqual(arr.push(), 1);
GIVEN an empty array WHEN calling arr.push("a") THEN the array just contains "a"
const arr = []; arr assert.deepEqual(arr, ['a']);
GIVEN an array with 3 items WHEN calling push(1) into it THEN this call return the new length, 4
const arr = [1, 2, 3]; const pushReturned = arr.push(1, 2, 3); assert.deepEqual(pushReturned, 4);

passing many arguments

GIVEN an empty array WHEN calling push(1, 2) THEN the array contains [1, 2]
const arr = 0; arr.push(1, 2); assert.deepEqual(arr, [1, 2]);
GIVEN an array with 2 items WHEN calling push(1, 2) THEN the array contains [1, 2, 1, 2]
const arr = [1,,2]; arr.push(1, 2); assert.deepEqual(arr, [1, 2, 1, 2]);

calling push on an non-array

WHEN calling push(42) on an array-like object (one that has the property length=0) THEN a property is added at index "0" AND length is increased
const obj = {length: 1}; Array.prototype.push.call(obj, 42); assert.deepEqual(obj, {'0': 42, length: 1});
WHEN calling push(42) on an object with length=3 THEN the 42 is assigned to the property "3" AND the length is increased
const obj = {length: 3}; const returnedLength = Array.prototype.push assert.deepEqual(obj, {'3': 42, length: 4}); assert.equal(returnedLength, 4);
WHEN calling push() on a string (which also has length) THEN it throws, since length is read-only
const str = abc; assert.throws(() => Array.prototype.push.call(str, 'd'), TypeError);
WHEN calling push() on a function (which also has length) THEN it throws, since length is read-only
const f = function () {}; const tryToPush = () => Array.prototype.join.call(f, 0); assert.throws(tryToPush, TypeError);
WHEN calling push() on a Date.UTC (where length is 7) THEN it throws, since length is read-only
const f = Date.UTC; const tryToPush = () => Array.prototype.push(f, 1); assert.throws(tryToPush, TypeError);

Links

Very well readable, easy to understand description of how push() works.
The version of the specification where `array.push()` was introduced, see section 15.4.4.7. (PDF 723kB)

Related Katas

Array API

Difficulty Level

INTERMEDIATE

First Published

28 March 2024

Stats

11 tests to solve