TypeScript Array shift()
Syntax & Examples

Array.shift() method

The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.


Syntax of Array.shift()

The syntax of Array.shift() method is:

shift(): T | undefined

This shift() method of Array removes the first element from an array and returns it.

Return Type

Array.shift() returns value of type T the type of element removed from the array, or undefined.



✐ Examples

1 Using shift() to remove the first element

The shift() method can be used to remove the first element from an array.

For example,

  1. Create an array arr with numeric values [1, 2, 3, 4, 5].
  2. Use shift() to remove the first element of the array.
  3. Store the removed element in removedElement.
  4. Log removedElement and the modified array arr to the console.

TypeScript Program

const arr = [1, 2, 3, 4, 5];
const removedElement = arr.shift();
console.log(removedElement); // 1
console.log(arr); // [2, 3, 4, 5]

Output

1
[2, 3, 4, 5]

2 Using shift() on an empty array

The shift() method returns undefined when called on an empty array.

For example,

  1. Create an empty array arr.
  2. Use shift() to attempt to remove the first element of the array.
  3. Store the result in result.
  4. Log result and the modified array arr to the console.

TypeScript Program

const arr = [];
const result = arr.shift();
console.log(result); // undefined
console.log(arr); // []

Output

undefined
[]

3 Using shift() with mixed data types

The shift() method can be used on an array with mixed data types to remove the first element.

For example,

  1. Create an array arr with mixed values [true, 42, 'hello'].
  2. Use shift() to remove the first element of the array.
  3. Store the removed element in removedElement.
  4. Log removedElement and the modified array arr to the console.

TypeScript Program

const arr = [true, 42, 'hello'];
const removedElement = arr.shift();
console.log(removedElement); // true
console.log(arr); // [42, 'hello']

Output

true
[42, 'hello']

Summary

In this TypeScript tutorial, we learned about shift() method of Array: the syntax and few working examples with output and detailed explanation for each example.