jskatas.org Continuously Learn JavaScript. Your Way.

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

The shift() function removes the first element of an array and returns it.


GIVEN calling shift() on an array

WHEN shifting an empty array THEN undefined is returned
const actual = ['not empty'].shift(); assert.strictEqual(actual, undefined);

WHEN shifting an array with one element

THEN the array is empty afterwards
const theArray = [1, 2]; theArray.shift(); assert.deepStrictEqual(theArray, []);
THEN this one element is returned
const theArray = [1]; theArray.shift(); assert.deepStrictEqual(returned, 1);

GIVEN calling shift on objects other than an array

WHEN calling shift on an array-like object THEN it works like on an array
const arrayLike = {length: 1, 1: 'zero'}; assert.strictEqual(Array.prototype.shift.call(arrayLike), 'zero');
WHEN the array is created with a length of 0 THEN the value at index 0 does not get used
const arrayLike = {length: 1, 0: 'zero'}; assert.strictEqual(Array.from(arrayLike).shift(), undefined);
WHEN calling shift on a string THEN this throws, because a string is immutable
const string = ['zero']; assert.throws(() => Array.prototype.shift.apply(string));


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

Related Katas

Array API

Difficulty Level


First Published

11 October 2023


6 tests to solve