TypeScript Array push()
Syntax & Examples

Array.push() method

The push() method adds one or more elements to the end of an array and returns the new length of the array.


Syntax of Array.push()

The syntax of Array.push() method is:

push(...items: T[]): number

This push() method of Array appends new elements to an array, and returns the new length of the array.

Parameters

ParameterOptional/RequiredDescription
itemsrequiredThe elements to add to the end of the array.

Return Type

Array.push() returns value of type number.



✐ Examples

1 Using push() to add elements to an array

The push() method can be used to add multiple elements to the end of an array.

For example,

  1. Create an array arr with initial values [1, 2, 3].
  2. Use push() to add the elements 4 and 5 to the end of the array.
  3. Store the new length of the array in newLength.
  4. Log the modified array arr and the new length newLength to the console.

TypeScript Program

const arr = [1, 2, 3];
const newLength = arr.push(4, 5);
console.log(arr); // [1, 2, 3, 4, 5]
console.log(newLength); // 5

Output

[1, 2, 3, 4, 5]
5

2 Using push() to add a single element

The push() method can be used to add a single element to the end of an array.

For example,

  1. Create an array arr with initial values ['a', 'b', 'c'].
  2. Use push() to add the element 'd' to the end of the array.
  3. Store the new length of the array in newLength.
  4. Log the modified array arr and the new length newLength to the console.

TypeScript Program

const arr = ['a', 'b', 'c'];
const newLength = arr.push('d');
console.log(arr); // ['a', 'b', 'c', 'd']
console.log(newLength); // 4

Output

['a', 'b', 'c', 'd']
4

3 Using push() to add elements of different types

The push() method can be used to add elements of different types to the end of an array.

For example,

  1. Create an array arr with initial values [1, 'apple', true].
  2. Use push() to add the elements 2 and 'banana' to the end of the array.
  3. Store the new length of the array in newLength.
  4. Log the modified array arr and the new length newLength to the console.

TypeScript Program

const arr = [1, 'apple', true];
const newLength = arr.push(2, 'banana');
console.log(arr); // [1, 'apple', true, 2, 'banana']
console.log(newLength); // 5

Output

[1, 'apple', true, 2, 'banana']
5

Summary

In this TypeScript tutorial, we learned about push() method of Array: the syntax and few working examples with output and detailed explanation for each example.