The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
The syntax of Array.unshift() method is:
unshift(...items: T[]): number
This unshift() method of Array inserts new elements at the start of an array and returns the new length of the array.
Parameter | Optional/Required | Description |
---|---|---|
items | required | The elements to add to the front of the array. |
Array.unshift() returns value of type number
.
The unshift() method can be used to add elements to the beginning of an array.
For example,
arr
with initial values [2, 3, 4].unshift()
to add the elements 0 and 1 at the beginning.newLength
.arr
and newLength
to the console.const arr = [2, 3, 4];
const newLength = arr.unshift(0, 1);
console.log(arr); // [0, 1, 2, 3, 4]
console.log(newLength); // 5
[0, 1, 2, 3, 4] 5
The unshift() method can add elements to an initially empty array.
For example,
arr
.unshift()
to add the elements 'a', 'b', and 'c' at the beginning.newLength
.arr
and newLength
to the console.const arr = [];
const newLength = arr.unshift('a', 'b', 'c');
console.log(arr); // ['a', 'b', 'c']
console.log(newLength); // 3
['a', 'b', 'c'] 3
The unshift() method can add a single element to the beginning of an array.
For example,
arr
with initial values [1, 2, 3].unshift()
to add the element 0 at the beginning.newLength
.arr
and newLength
to the console.const arr = [1, 2, 3];
const newLength = arr.unshift(0);
console.log(arr); // [0, 1, 2, 3]
console.log(newLength); // 4
[0, 1, 2, 3] 4
In this TypeScript tutorial, we learned about unshift() method of Array: the syntax and few working examples with output and detailed explanation for each example.