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.
array.push(element1, element2, elementN)
element1, element2, ... elementN
: these are the elements we want to push to the array. There can be more than one elements.
This method returns the new array length.
// 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)
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.