5 Ways To Add Elements To Javascript Array (Simple Examples)

Welcome to a quick tutorial on how to add elements to a Javascript array. New to Javascript and the whole array thing? Yes, creating a new array is straightforward, but it can be quite confusing when it comes to adding elements to an existing one.

There are a couple of different ways to add elements to an array in Javascript:

  1. ARRAY.push("ELEMENT") will append to the end of the array.
  2. ARRAY.unshift("ELEMENT") will append to the start of the array.
  3. ARRAY[ARRAY.length] = "ELEMENT" acts just like push, and will append to the end.
  4. ARRAYA.concat(ARRAYB) will join two arrays together.
  5. ARRAY.splice(INDEX, 0, "ELEMENT") will insert a new element at the specified index.

But just how does each of these methods work exactly? Let us walk through more examples, read on to find out!

 

 

TLDR – QUICK SLIDES

[web_stories_embed url=”https://code-boxx.com/web-stories/how-to-add-elements-to-javascript-array/” title=”How To Add Elements To Javascript Array” poster=”https://code-boxx.com/wp-content/uploads/2021/11/STORY-JS-20230518.webp” width=”360″ height=”600″ align=”center”]

Fullscreen Mode – Click Here

 

TABLE OF CONTENTS

 

 

JS APPEND TO ARRAY

All right, let us now get into the ways to append elements to an array.

 

METHOD 1) PUSH (ADD TO END)

1-push.html
// (A) PUSH - ADD TO END
var arr = ["First", "Second"];
arr.push("Third");
console.table(arr); // First, Second, Third

// (B) WE CAN ALSO ADD MULTIPLE AT ONCE
arr.push("Forth", "Fifth");
console.table(arr); // First, Second, Third, Forth, Fifth

As in the introduction above, the push() function is used to append elements to the end of an existing array. Yes, take note that we can append multiple elements at once.

 

 

METHOD 2) UNSHIFT (ADD TO FRONT)

2-unshift.html
// (A) UNSHIFT - ADD TO FRONT
var arr = ["First", "Second"];
arr.unshift("Third");
console.table(arr); // Third, First, Second

// (B) WE CAN ALSO ADD MULTIPLE AT ONCE
arr.unshift("Forth", "Fifth");
console.table(arr); // Forth, Fifth, Third, First, Second

The unshift() function is the cousin of push(). It adds elements to the front of the array instead of the end. Same story, we can use it to append multiple elements at once.

 

METHOD 3) ASSIGN STATEMENT

3-statement.html
var arr = ["First", "Second"];
arr[arr.length] = "Third";
console.table(arr); // First, Second, Third

This is an “alternative” to the push() function. As you already know, we can use ARRAY[N] = VALUE directly to replace or insert an element. Thus, ARRAY[ARRAY.length] = VALUE will simply append a new element to the end of the array.

 

 

METHOD 4) CONCAT (JOIN ARRAYS)

4-concat.html
// (A) TWO DIFFERENT ARRAYS
var arrA = ["First", "Second"];
var arrB = ["Third", "Forth"];
 
// (B) CONCAT COMBINE
var combined = arrA.concat(arrB);
console.table(combined); // First, Second, Third, Forth

As you guys already know, we can combine two strings together – By either using the + operator, or concat() function. Yes, we can use the concat() function on arrays to combine them as well.

P.S. Short note that we can also use the + operator on arrays as well, ARRAY A + ARRAY B. But this will result in a string with the “flattened array” instead. In the above example, that will end up with First,SecondThird,Forth.

 

EXTRA) JOIN ARRAY INTO STRING

e-join.html
// (A) AN ARRAY
var elements = ["Wind", "Water", "Fire", "Earth"];

// (B) JOIN ARRAY INTO STRING
var quote = elements.join(" ");
console.log(quote); // Wind Water Fire Earth

// WE CAN ALSO SPECIFY THE "JOINTS"
// quote = elements.join("-");
// console.log(quote); // Wind-Water-Fire-Earth

// (C) COMPLETE THE STORY
quote += ". Long ago, the four nations lived together in harmony.";
console.log(quote); // Wind Water Fire Earth. Long ago...

While we are still on the topic of “array to string”, here is a small extra. If you want to “combine” an array into a string, use the join() function. Very handy if you want to turn an array into a string.

 

METHOD 5) SPLICE

5-splice.html
// (A) ONE PARAMETER
var arr = ["First", "Second", "Third", "Forth", "Fifth"];
arr.splice(2); // keep first 2 elements
console.table(arr); // First, Second

// (B) TWO PARAMETERS
arr = ["First", "Second", "Third", "Forth", "Fifth"];
arr.splice(1, 2); // remove 2 elements from index 1
console.table(arr); // First, Forth, Fifth

// (C) THREE OR MORE PARAMETERS
// (C1) INSERT SINGLE
arr = ["First", "Second", "Third"];
arr.splice(1, 0, "FOO"); // insert "foo" at index 1
console.table(arr); // First, FOO, Second, Third
 
// (C2) INSERT MULTIPLE
arr = ["First", "Second", "Third"];
arr.splice(1, 0, "FOO", "BAR"); // insert "foo", "bar" at index 1
console.table(arr); // First, FOO, BAR, Second, Third
 
// (C3) REPLACE
arr = ["First", "Second", "Third"];
arr.splice(0, 2, "FOO"); // remove 2 elements from index 0, then insert "foo"
console.table(arr); // FOO, Third

Finally, the splice() function is a rather confusing one, but it is also very useful.

  • When we input one parameter, splice(N) will keep N number of elements from the start of the array. This is, only ARRAY[0] to ARRAY[N-1] will remain. Not what we want though.
  • When we input two parameters, splice(N, M) will remove M number of elements from the array, starting from ARRAY[N]. Not what we want here either.
  • Finally, splice(N, M, O, O, ...) is what we are looking at. Same as above, this will remove M number of elements starting from ARRAY[N], then replace it with O. But if we set M to 0, no elements will be removed – This will act as an “insert in-between” instead. Pretty cool.

 

 

DOWNLOAD & NOTES

Here is the download link to the example code, so you don’t have to copy-paste everything.

 

SORRY FOR THE ADS...

But someone has to pay the bills, and sponsors are paying for it. I insist on not turning Code Boxx into a "paid scripts" business, and I don't "block people with Adblock". Every little bit of support helps.

Buy Me A Coffee Code Boxx eBooks

 

EXAMPLE CODE DOWNLOAD

Click here for the source code on GitHub gist, just click on “download zip” or do a git clone. I have released it under the MIT license, so feel free to build on top of it or use it in your own project.

 

EXTRA BITS & LINKS

That’s all for this guide, and here is a small section on some extras and links that may be useful to you.

 

THE SUMMARY

Function/Statement Description Reference Link
push() Add new elements to the end of the array. Click Here
unshift() Add new elements to the start of the array. Click Here
ARRAY[ARRAY.length] = VALUE The statement way of adding a new element to the end.
concat() Joins two arrays together. Click Here
splice() Remove, replace, or insert elements. Click Here

 

TUTORIAL VIDEO

 

INFOGRAPHIC CHEAT SHEET

Add Elements To Javascript Array (click to enlarge)

 

THE END

Thank you for reading, and we have come to the end of this guide. I hope that it has helped you with your project, and if you want to share anything with this guide, please feel free to comment below. Good luck and happy coding!

3 thoughts on “5 Ways To Add Elements To Javascript Array (Simple Examples)”

  1. Hi there,
    I found your article really interesting but I think there’s something you need to fix at the beginning of it. It is the first reference to *shift* that should be *unshift* instead, and as it is the first one. That’s what I took first and tried it and failed in my case. The rest of the article is correct, only the first reference to the method is incorrect.
    Thank you for this article, it’s really good.

  2. Hello there!
    I love your work, I love your way of coding, precise, concise, really neat. Thank you so much for this wonderful site. Everything is understandable at first sight, or almost in my case 🙂
    Reading you is also a pleasure. Take good care of you and keep on the fun side. You’re great.

Leave a Comment

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