Start learning free

LESSON 99 OF 348 · ARRAYS I

Array Push in TypeScript: Appending Items with push()

Lesson Read the full explanation

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 = ["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]

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

    TYPESCRIPT · ARRAYS I

    Array Push in TypeScript, explained

    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.

    1. Add a fruit. Call push on fruits with "apple". The array now has four elements, with "apple" last.
    2. Add two ages. Call push on ages once with 10 and once with 23. Order matters: each call appends at the end, so 10 goes in first and 23 ends 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; and other.push("fig"), fruits contains "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 unshift instead.
    • Pushing in a loop is normal. Building a result array one item at a time is the usual pattern, and push is fast enough for it.

    Key takeaways

    • arr.push(x) appends x to the end of arr, and arr.push(a, b) appends both in order.
    • The array is changed in place, and push returns the new length.
    • The type of the pushed value must match the array's element type.
    • A const array can still grow.
    Keep going with TypeScriptAbout 340 step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free