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.
Free plan: 30 tutor messages. Premium is unlimited.
Saved
Ctrl + Enter to check
