mozilla
Your Search Results

    Array.prototype.push()

    Summary

    The push() method adds one or more elements to the end of an array and returns the new length of the array.

    Syntax

    arr.push(element1, ..., elementN)

    Parameters

    elementN
    The elements to add to the end of the array.

    Returns

    The new length property of the object upon which the method was called.

    Description

    The push method appends values to an array.

    push is intentionally generic. This method can be used with call() or apply() on objects resembling arrays. The push method relies on a length property to determine where to start inserting the given values. If the length property cannot be converted into a number, the index used is 0. This includes the possibility of length being nonexistent, in which case length will also be created.

    The only native, array-like objects are strings, although they are not suitable in applications of this method, as strings are immutable.

    Examples

    Example: Adding elements to an array

    The following code creates the sports array containing two elements, then appends two elements to it. The total variable contains the new length of the array.

    var sports = ['soccer', 'baseball'];
    var total = sports.push('football', 'swimming');
    
    console.log(sports); // ['soccer', 'baseball', 'football', 'swimming']
    console.log(total);  // 4
    

    Example: Merging two arrays

    This example uses apply() to push all elements from a second array.

    var vegetables = ['parsnip', 'potato'];
    var moreVegs = ['celery', 'beetroot'];
    
    // Merge the second array into the first one
    // Equivalent to vegetables.push('celery', 'beetroot');
    Array.prototype.push.apply(vegetables, moreVegs);
    
    console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']
    

    Specifications

    Specification Status Comment
    ECMAScript 3rd Edition Standard Initial definition. Implemented in JavaScript 1.2.
    ECMAScript 5.1 (ECMA-262)
    The definition of 'Array.prototype.push' in that specification.
    Standard  
    ECMAScript 6 (ECMA-262)
    The definition of 'Array.prototype.push' in that specification.
    Draft  

    Browser compatibility

    Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
    Basic support 1.0 1.0 (1.7 or earlier) 5.5 (Yes) (Yes)
    Feature Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
    Basic support (Yes) (Yes) (Yes) (Yes) (Yes) (Yes)

    See also

    Hide Sidebar