Start learning free

LESSON 112 OF 573 · ARRAYS I

Appending Item to Array in TypeScript

Lesson

We can add elements to the end of an array using the .push() method.

.push() takes one or more items and "pushes" them onto the end of the array:

let myArray: (string | number | boolean)[] = ["Hello world!"];

// Pushing one element:
myArray.push(44);
console.log(myArray); // Output: [ 'Hello world!', 44 ]

// Pushing three elements:
myArray.push("apples", true, 12);
console.log(myArray); // Output: [ 'Hello world!', 44, 'apples', true, 12 ]

The array holds strings, numbers and booleans, so its type lists all three. With a plain string[], pushing 44 would be a compile error.


Assignment
Follow the Coding Tutorial and let's play with some arrays.


Hint
Look at the examples above if you get stuck.


STEP 1 OF 2
    Ctrl + Enter to check