TypeScript Array push() Method
The Array.push() method in TypeScript is a built-in function used to append one or more elements to the end of an array. It modifies the original array and returns the new length of the array.
Syntax
Here is the syntax for using the push() method:
array.push(element1, ..., elementN)
Parameter: This method accept a single parameter as mentioned above and described below:
- element1, …, elementN: The elements to add to the end of the array.
Return Value: This method returns the length of the new array.
- The method returns the new length of the array after the elements have been added.
Examples of TypeScript Array push() Method
Example 1: Adding a Single Element
In this example, we add a single element to an array.
let numbers: number[] = [11, 89, 23, 7, 98];
let newLength: number = numbers.push(8);
console.log(numbers);
console.log(newLength);
Output:
[11, 89, 23, 7, 98, 8]
6
Example 2: Adding Multiple Elements
In this example, we add multiple elements to an array.
let values: number[] = [2, 5, 6, 3, 8, 9];
let newLength: number = values.push(0, 5, 12, 9);
console.log(values);
console.log(newLength);
Output:
[2, 5, 6, 3, 8, 9, 0, 5, 12, 9]
10
let emptyArray: number[] = [];
emptyArray.push(1, 2, 3);
console.log(emptyArray);
Output: [1, 2, 3]
Is it possible to chain push() method calls?
No, since the push() method returns the new length of the array, not the array itself. Therefore, chaining push() calls directly is not possible.