How to add elements to an existing array dynamically in JavaScript ?
An array is a JavaScript object that can hold multiple values at a time, irrespective of the data type.
Example:
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.
console.log(a[1]);
Above statement prints ‘For’ from the above example in the console window.
Output:
For
or
document.write(a[1]);
Output:
For
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
<script> // JavaScript Array Initialization var a = [ 'Hi' , 'There' ]; // New element added dynamically. a[3] = 'Geeks' ; document.write(a[3]); document.write( "<br>" ); document.write(a[2]); </script> |
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
<script> // JavaScript Array Declared var a = []; // Elements pushed into the // array using push() method a.push( 'Geeks' ); a.push( 'For' ); a.push( 'Geeks' ); // Obtaining the value document.write(a); </script> |
Output:
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.