Similar to JavaScript, which is a subset of TypeScript, we can add elements to an array using the unshift()
method. The unshift()
method adds these elements to the beginning of the array.
array.unshift(element*)
elements*
: This represents the element or elements we want to add to the beginning of the array
.
It returns the new length of the array.
// 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"]// add elements to the arraysconsole.log("length of modified names array : ", names.unshift("Bianca"))console.log("length of modified numbers array: ", numbers.unshift(3, 43, 55, 23))console.log("length of modified cars array: ", cars.unshift("G-Wagon", "Volkswagen"))// print modified arraysconsole.log("\n")console.log(names)console.log(numbers)console.log(cars)
unshift()
method and print the result, that is the lengths of the modified arrays, to the console.