Categories
JavaScript Basics

How to Append Items to a JavaScript Array?

Spread the love

There are a few ways to append items to an array in JavaScript.

In this article, we’ll look at how to do that in different ways.

Array.prototype.push

The push method appends one more item into an array.

We can use it by writing:

arr.push('foo');

to add 'foo' to arr .

Also, we can add multiple elements to an array with it:”

arr.push('foo', 'bar');

Then both 'foo' and 'bar' are added to arr in the same order.

This also means we can use the spread operator to append then entries of an array with push :

arr.push(...['foo', 'bar']);

That does the same thing as the previous example.

Spread Operator

We can use the spread operator to create a new array with new entries added to it.

For instance, we can write:

arr = [...arr, 'foo', 'bar'];

We used the spread operator to spread the existing entries of arr into a new array.

Then we added 'foo' and 'bar' to it at the end.

Then we assigned the new array back to arr .

Array.prototype.splice

Also, we can use the splice method fo the array instance to append to an array.

It takes 3 or more arguments, which are the start index, deletes count, and items, we want to add.

To add items into an array, we can write:

arr.splice(arr.length, 0. 'foo', 'bar');

In the code above, we indicated that we want to start at the last index of the array + 1 with arr.length .

0 means we remove nothing.

The 'foo' and 'bar' are the items we add.

Set an Item to the length Index

JavaScript arrays aren’t fixed length, so we can assign an entry to any index.

If we want to append an entry to an array, then we can set it using the bracket notation as follows:

arr[arr.length] = 'foo';

Then we can append 'foo' to arr since arr.length is one index beyond the end index of the original array.

Array.prototype.concat

We can use the concat method of the array instance to append one or more entries into the array.

For instance, we can write:

arr = arr.concat('foo', 'bar');

Also, we can write:

arr = arr.concat(...['foo', 'bar']);

Either way, we pass in one or more arguments for the items we want to append to the new array in addition to the existing ones.

concat returns a new array, so we’ve to assign it to a variable to access it.

Mutate or Not

It’s better that we don’t mutate the array so that we keep the existing value.

It’s easier to test and track immutable data.

Therefore, it’s preferred to not mutate data if possible.

Conclusion

In JavaScript, there are many ways to append an item to an array.

We can use the spread operator, or we can use various array methods to do the same thing.

Some operators or methods mutate and some don’t, so we’ve to be careful when using them.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *