How to add one or more elements to an array in TypeScript

Overview

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.

Syntax

array.unshift(element*)
Syntax for unshift() method in TypeScript

Parameters

elements* : This represents the element or elements we want to add to the beginning of the array.

Return value

It returns the new length of the array.

Example

// create arrays in TypeScript
let 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 arrays
console.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 arrays
console.log("\n")
console.log(names)
console.log(numbers)
console.log(cars)

Explanation

  • Lines 2–5: We create some arrays.
  • Lines 8–10: We add elements to the arrays using the unshift() method and print the result, that is the lengths of the modified arrays, to the console.
  • Lines 14–16: We print the modified arrays to the console.