What is the shift() method of an array in TypeScript?

Overview

The shift() method of an array is used to remove and return the first element of the array. It is similar to the shift() method of JavaScript, which is a subset of TypeScript.

Syntax

array.shift()
Syntax for the shift() method in TypeScript

Parameters

array: This is the array that we want to remove the first element of.

Return value

The value returned is the removed element of the array.

Example

// create arrays in TypeScript
let names: string[] = ["Theodore", "James", "Peter", "Amaka"]
let numbers : Array<number>;
numbers = [12, 34, 5, 0.9]
let cars : Array<string> = ["Porsche", "Toyota", "Lexus"]
// remove and print first elements of the arrays
console.log("removed element: ", names.shift())
console.log("removed element: ", numbers.shift())
console.log("removed element: ", cars.shift())
// print modified arrays
console.log("\nModified Arrays:")
console.log(names)
console.log(numbers)
console.log(cars)

Explanation

  • Lines 2–5: We create arrays in TypeScript.
  • Lines 8–10: We call the shift() method on the arrays, which removes and returns the first elements of the arrays. We then print the removed elements.
  • Lines 14–16: We print the modified array to the console.

Free Resources