The Array.shift() method is an inbuilt TypeScript function used to remove the first element from an array and return that element. This operation modifies the original array by removing the first element.
Syntax
array.shift(); Parameter: This method does not accept any parameter.
Return Value: This method returns the removed single value of the array.
The below example illustrates the Array shift() method in TypeScriptJS:
Example 1: Removing the First Element
In this example The shift() method removes and returns the first element (11) from the numbers array.
let numbers: number[] = [11, 89, 23, 7, 98];
let firstElement: number = numbers.shift();
console.log(firstElement); // Output: 11
console.log(numbers); // Output: [ 89, 23, 7, 98 ]
Output:
11
[ 89, 23, 7, 98 ]
Example 2: Removing Elements from a Queue
In this example The shift() method removes and returns the first two elements (2 and 5) from queue.
let queue: number[] = [2, 5, 6, 3, 8, 9];
let firstInQueue: number = queue.shift();
let secondInQueue: number = queue.shift();
console.log(firstInQueue); // Output: 2
console.log(secondInQueue); // Output: 5
console.log(queue); // Output: [ 6, 3, 8, 9 ]
Output:
2
5
[ 6, 3, 8, 9 ]