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

ParameterOptional/RequiredDescription
itemsrequiredThe 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,

  1. Create an array arr with initial values [2, 3, 4].
  2. Use unshift() to add the elements 0 and 1 at the beginning.
  3. Store the new length of the array in newLength.
  4. Log arr and newLength 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,

  1. Create an empty array arr.
  2. Use unshift() to add the elements 'a', 'b', and 'c' at the beginning.
  3. Store the new length of the array in newLength.
  4. Log arr and newLength 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,

  1. Create an array arr with initial values [1, 2, 3].
  2. Use unshift() to add the element 0 at the beginning.
  3. Store the new length of the array in newLength.
  4. Log arr and newLength 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.