How to push an element to the end of an array in TypeScript
Overview
We push an element to an array in TypeScript, similarly to pushing an element in JavaScript. We use the push() method for this purpose. In TypeScript, we can push or add one or more elements to the end of an Array.
Syntax
array.push(element1, element2, elementN)
Syntax for the push() method in TypeScript
Parameters
element1, element2, ... elementN: these are the elements we want to push to the array. There can be more than one elements.
Return Value
This method returns the new array length.
Example
// create arrays in TypeScriptlet names: string[] = ["Theodore", "James", "Peter", "Amaka"]let numbers : Array<number>;numbers = [12, 34, 5, 0.9]let cars : Array<string> = ["Porsche", "Toyota", "Lexus"]// push in some elements and print returned valueconsole.log(names.push("Elizabeth"));console.log(numbers.push(1, 2, 3));console.log(cars.push("Ferrari"))// print new arraysconsole.log(names)console.log(numbers)console.log(cars)
Explanation
- Line 2–5: We create some arrays in TypeScript and initialize them.
- Line 8–10: We use
push()method to push the new elements to the end of an array. Print the results, which are the length of the new arrays, to the console. - Line 13 and 14: The new arrays are printed to the console.