00 Votes

JavaScript: Add Array Elements

Question by Compi | 2015-08-10 at 22:39

Using JavaScript, you can easily specify an array, for example with "var arr = [1, 2, 3]". But what about adding some new further elements to an existing array?

Is it possible to add an element to an existing JavaScript array without re-creating the entire array? Is there any function I can use for that?

ReplyPositiveNegative
0Best Answer0 Votes

Yes, there is a function available for that. It is called .push() and it can be used like that:

var arr = [1, 2, 3];
arr.push(4);

In this example, we are creating an array consisting of the elements 1, 2 and 3. After that, we are using .push(4) to add one further element - the number 4 - to the array. This makes our new array containing the elements 1, 2, 3 and 4.

Another way, we can use to enlarge an array, is to just access an index that is not yet in use.

var arr = [1, 2, 3];
arr[3] = 4;

This example is creating the same result like it was in this first example. The elements 1, 2 and 3 do have the indices 0, 1 and 2. With setting the element with the non-existing index 3, we are accordingly extending the array.

Instead of directly hard coding the index, we can also use the property "length" of the array, which is giving us the length of the array:

var arr = [1, 2, 3];
arr[arr.length] = 4;
arr[arr.length] = 5;

With this code, we are creating an array containing the elements 1, 2, 3, 4 and 5. The array length is 3 in the second line and 4 in the third line. Therefore, by doing this, we are also adding a new element at the end of the array.

By the way, the index, we are using here, do not have to be the next available or free index. We are also free to directly access the index 10 or 100, for example, which however will result in an array containing a great number of undefined elements.
2015-08-13 at 16:48

ReplyPositive Negative
Reply

Related Topics

Important Note

Please note: The contributions published on askingbox.com are contributions of users and should not substitute professional advice. They are not verified by independents and do not necessarily reflect the opinion of askingbox.com. Learn more.

Participate

Ask your own question or write your own article on askingbox.com. That’s how it’s done.