TypeScript Array unshift()
Syntax & Examples
Array.unshift() method
The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.
Syntax of Array.unshift()
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.
Parameters
Parameter | Optional/Required | Description |
---|---|---|
items | required | The elements to add to the front of the array. |
Return Type
Array.unshift() returns value of type number
.
✐ Examples
1 Using unshift() to add elements at the beginning
The unshift() method can be used to add elements to the beginning of an array.
For example,
- Create an array
arr
with initial values [2, 3, 4]. - Use
unshift()
to add the elements 0 and 1 at the beginning. - Store the new length of the array in
newLength
. - Log
arr
andnewLength
to the console.
TypeScript Program
const arr = [2, 3, 4];
const newLength = arr.unshift(0, 1);
console.log(arr); // [0, 1, 2, 3, 4]
console.log(newLength); // 5
Output
[0, 1, 2, 3, 4] 5
2 Using unshift() with an empty array
The unshift() method can add elements to an initially empty array.
For example,
- Create an empty array
arr
. - Use
unshift()
to add the elements 'a', 'b', and 'c' at the beginning. - Store the new length of the array in
newLength
. - Log
arr
andnewLength
to the console.
TypeScript Program
const arr = [];
const newLength = arr.unshift('a', 'b', 'c');
console.log(arr); // ['a', 'b', 'c']
console.log(newLength); // 3
Output
['a', 'b', 'c'] 3
3 Using unshift() to add a single element
The unshift() method can add a single element to the beginning of an array.
For example,
- Create an array
arr
with initial values [1, 2, 3]. - Use
unshift()
to add the element 0 at the beginning. - Store the new length of the array in
newLength
. - Log
arr
andnewLength
to the console.
TypeScript Program
const arr = [1, 2, 3];
const newLength = arr.unshift(0);
console.log(arr); // [0, 1, 2, 3]
console.log(newLength); // 4
Output
[0, 1, 2, 3] 4
Summary
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.