The shift() method removes the first element from an array and returns that removed element. This method changes the length of the array.
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.
Array.shift() returns value of type T
the type of element removed from the array, or undefined
.
The shift() method can be used to remove the first element from an array.
For example,
arr
with numeric values [1, 2, 3, 4, 5].shift()
to remove the first element of the array.removedElement
.removedElement
and the modified array arr
to the console.const arr = [1, 2, 3, 4, 5];
const removedElement = arr.shift();
console.log(removedElement); // 1
console.log(arr); // [2, 3, 4, 5]
1 [2, 3, 4, 5]
The shift() method returns undefined when called on an empty array.
For example,
arr
.shift()
to attempt to remove the first element of the array.result
.result
and the modified array arr
to the console.const arr = [];
const result = arr.shift();
console.log(result); // undefined
console.log(arr); // []
undefined []
The shift() method can be used on an array with mixed data types to remove the first element.
For example,
arr
with mixed values [true, 42, 'hello'].shift()
to remove the first element of the array.removedElement
.removedElement
and the modified array arr
to the console.const arr = [true, 42, 'hello'];
const removedElement = arr.shift();
console.log(removedElement); // true
console.log(arr); // [42, 'hello']
true [42, 'hello']
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.