JS Built-ins
← Array163 / 226
ArrayArray.prototype.shiftbeginner

Array.prototype.shift() β€” shifting an empty array

πŸ“– Usage Example
const arr = []
arr.shift()  // β†’ undefined  (empty array)

shift() returns undefined when called on an empty array β€” handle this case if needed.

shift() on an empty array

When called on an empty array, shift() returns undefined rather than throwing an error.

([] as number[]).shift() // undefined

This is important to know when writing defensive code.

πŸ’‘ Hints (2)
  • β€’ `shift()` on an empty array returns `undefined` β€” it does not throw.
  • β€’ Use a type assertion `([] as number[])` to satisfy TypeScript.