What push does
The push method adds items to the end of an array. It changes the array it is called on, so the array is longer afterwards. You can pass one item or several, and they are added in the order you write them.
const fruits: string[] = ["mango", "kiwi"];
fruits.push("apple");
console.log(fruits); // [ 'mango', 'kiwi', 'apple' ]
fruits.push("pear", "plum");
console.log(fruits); // [ 'mango', 'kiwi', 'apple', 'pear', 'plum' ]
Notice that fruits is declared with const and still changes. const stops you from assigning a different array to the variable, but it doesn't freeze the array's contents.
What push returns
The call push returns the new length of the array, not the array itself. Most of the time you ignore it and write the call as a statement. It matters when you try to chain calls or store the result:
const fruits: string[] = ["mango", "kiwi", "grapefruit"];
const result = fruits.push("apple");
console.log(result); // 4
console.log(fruits); // [ 'mango', 'kiwi', 'grapefruit', 'apple' ]
A common mistake is to write fruits = fruits.push("apple"). That would replace the array with the number 4 (the compiler reports that as a type error). Just call fruits.push("apple") and keep using fruits.
Types and push
TypeScript checks what you push against the array's element type. An array of type number[] accepts numbers only:
const ages: number[] = [14, 32];
ages.push(10); // fine
ages.push("ten"); // the compiler reports an error: a string is not a number
The same happens without an annotation, because the type is inferred from the initial values. The array ["Hello world!"] has the type string[], so pushing the number 44 into it is reported as an error. To hold mixed values you have to say so, with a union type:
const items: (string | number | boolean)[] = ["Hello world!"];
items.push(44);
items.push("apples", true, 12);
console.log(items); // [ 'Hello world!', 44, 'apples', true, 12 ]
A type error doesn't stop the compiler from producing JavaScript, so a mistyped push would still run and add the wrong kind of value. Read the compiler's messages instead of ignoring them.
Building an array with push
Because push works on an array of any length, it is the usual way to build a result one item at a time. Start with an empty array that has an explicit element type, then push inside a loop:
const squares: number[] = [];
for (let i = 1; i <= 4; i++) {
squares.push(i * i);
}
console.log(squares); // [ 1, 4, 9, 16 ]
The annotation matters here. A bare [] has no items to infer a type from, so without : number[] the compiler has no element type to enforce, and a push of a string would go unreported. Writing the type down lets it check every later push.
The lesson's exercise
The starting code has two arrays: fruits with three strings and ages with four numbers. The exercise has two steps.
- Add a fruit. Call
pushonfruitswith"apple". The array now has four elements, with"apple"last. - Add two ages. Call
pushonagesonce with10and once with23. Order matters: each call appends at the end, so10goes in first and23ends up last.
let fruits: string[] = ["mango", "kiwi", "grapefruit"];
let ages: number[] = [14, 32, 50, 21];
fruits.push("apple");
ages.push(10);
ages.push(23);
Afterwards fruits is ["mango", "kiwi", "grapefruit", "apple"] and ages is [14, 32, 50, 21, 10, 23]. The single call ages.push(10, 23) would give the same array, since push accepts several values, but the lesson uses one call per value.
Gotchas
- It modifies the array in place. Every variable that refers to the same array sees the change. After
const other = fruits;andother.push("fig"),fruitscontains"fig"too, because both names point to one array. - Pushing an array adds one element.
a.push([1, 2])appends a single item that is itself an array. To append the items of another array, use spread:a.push(...b). - The new item goes last. To add at the front, use
unshiftinstead. - Pushing in a loop is normal. Building a result array one item at a time is the usual pattern, and
pushis fast enough for it.
Key takeaways
arr.push(x)appendsxto the end ofarr, andarr.push(a, b)appends both in order.- The array is changed in place, and
pushreturns the new length. - The type of the pushed value must match the array's element type.
- A
constarray can still grow.