TypeScript Array unshift() Method

Last Updated : 15 Jul, 2024

The Array.unshift() method in TypeScript is an inbuilt function used to add one or more elements to the beginning of an array. It modifies the original array and returns the new length of the array.

Syntax

array.unshift( element1, ..., elementN )

Parameter

This method accepts n number of similar elements.

  • element1, ..., elementN : This parameter is the elements to add to the front of the array.

Return Value

  • The method returns the new length of the array after the elements have been added.

Examples of TypeScript Array unshift() Method

Example 1: Adding a Single Element

TypeScript
let arr: number[] = [2, 3, 4];
let newLength: number = arr.unshift(1);
console.log(newLength);
console.log(arr);

 
Output:  

4
[1,2,3,4]

Example 2:  Adding Multiple Elements

TypeScript
let arr: string[] = ["f", "o", "r"];
let newLength: number = arr.unshift("G", "e", "e", "k", "s");
console.log(newLength);
console.log(arr);

 
Output:  

8
["G", "e", "e", "k", "s", "f", "o", "r"]
Comment
Article Tags:

Explore