Skip to content
Related Articles

Related Articles

How to add elements to an existing array dynamically in JavaScript ?

View Discussion
Improve Article
Save Article
  • Last Updated : 16 Jul, 2020

An array is a JavaScript object that can hold multiple values at a time, irrespective of the data type.


var a = ['Geeks', 'For', 'Geeks', 1];

In the above example, “Geeks” is of type “string” while 1 is of “integer” type. An array can also store JavaScript objects. JavaScript arrays are dynamic in nature, they do not need the size during initialization. They are accessed using numbered indexes.


Above statement prints ‘For’ from the above example in the console window.







To add elements into an array dynamically in JavaScript, the programmer can use any of the following methods.

Method 1: Use number indexes to add an element to the specified index.


    // JavaScript Array Initialization
    var a = ['Hi', 'There'];
    // New element added dynamically.
    a[3] = 'Geeks';

Output: On the console window

It can be seen that index of {0, 1} was declared only. Index 3 was dynamically created and initialized to ‘Geeks’. Index 2 was created automatically and initialized to undefined, to keep up the ordering.

Method 2: Use push() method is used to add element at the end of the array.


    // JavaScript Array Declared
    var a = [];
    // Elements pushed into the 
    // array using push() method
    // Obtaining the value


The console window shows an array object containing 3 values, they are [‘Geeks’, ‘For’, ‘Geeks’]. The push() method maintains the ordering of indexes by adding the new elements at the end of the array and returns the new length of the array.

My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!