Preparing for Java and Spring Boot Interview?

Join my Newsletter, its FREE

How to append an element to an array in JavaScript? Example Tutorial

Appending means adding an element at the end of the array and before we do that, we need to have a good understanding of an array in javaScript.  What is an array? An array is a single variable that is used to store different elements. This means that JavaScript array(s) can hold different types of data like the number, string, boolean and object values at the same time. Unlike in Java, sorry You can’t do that. It is strongly typed in fact from creation time you would specify what type of data is coming in and its length. And you can’t do otherwise once you have stated the type of data and length any attempts to do that leads to compilation error.
Also, the length of an array is dynamically sized and can keep growing. In other words, you don’t need to specify the array size upfront. You can access the values by referring to an index number. The index number starts from zero as you can see from the image below. The first item in the array is index 0, the second item, index 1. the third item, index 2. E.t.c

 I have been sharing a lot of Javascript resources like the best JavaScript courses, books, websites, and Javascript interview questions, along with many JavaScript and React tutorials. In the past, we have seen how to loop over the array and how to check if an element exists in an array or not, and today we will see how to append something to the JavaScript array. 

Know that JavaScript Array Iteration methods operate on every array item.

There are different ways to create an array in javaScript but the more preferred and common way to create an array is to use the array literal notation, The array literal form uses the square brackets [] to wrap a comma-separated list of elements. The following example creates the colors array that holds three strings:

  1. let colors = ['red', 'green', 'blue'];
You can as well create an empty array for later use by doing the following:

  1. Let my_Array = [];

 Arrays in JavaScript has the following inbuilt methods to make your task(s) easier:

  • The join() method also joins all array elements into a string.
  • The pop() method returns the value that was "popped out"
  • The push() method adds a new element to an array (at the end). When you work with arrays, it is easy to remove elements and add new elements.
  • The shift() method removes the first array element and "shifts" all other elements to a lower index and returns the value that was "shifted out".
  • The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements, and returns the new array length.
  • The splice() method can be used to add new items to an array, specifying what index you want to add the new items too.
  • The concat() method creates a new array by merging (concatenating) existing arrays, Note that The concat() method does not change the existing arrays. It always returns a new array. The concat() method can take any number of array arguments.




2 ways to append an element to an array in JavaScript [Mutative]

Here are 5 ways to add an item to the end of an array. push, splice, and length will mutate the original array. Whereas concat and spread will not and will instead return a new array. Which is the best depends on your use case.

This will change the original array
  1. const array = ['boy'];
  2. array.push('boy');
  3. array.splice(array.length, 0, 'boy');
  4. array[array.length] = 'boy';

Result

['boy', 'boy']

Non-Mutative

This will create a new array and the original array remains unchanged.

  1. const original = ['girl'];
  2. let newArray;
  3. newArray = original.concat('lady');
  4. newArray = [...original, 'lady'];

 // Result

newArray; // ['girl', 'lady']

original; // ['girl']

 






3 Ways to Append Item to Array (Mutative)


Let's look at the 3 ways we can push an item to an array. This will be the mutative way, meaning it will change the original array.

How to append an element to an array in JavaScript? Example Tutorial


Fig 1.0: Appending element in JavaScript

1. The push method

The simplest way to add items to the end of an array is to use push.

  1. const fruits = ['apple', 'lemon'];
  2. zoo.push('grape');
  3. console.log(fruits); // ['apple', 'lemon','grape']
  4. const color = ['white', 'black'];
  5. const numbers = ['5', '2', '9'];
  6. color .push(...numbers);
  7. console.log(color); // ['white', 'black','5', '2', '9']


2. The splice method

At first glance, this method can seem super needy because we're passing a bunch of arguments. That's because this method can add or remove array items.

So lastly, let us check this:

  1. const foods = ['rice', 'beans'];
  2. foods.splice(
  3. foods.length, // We want add at the END of our array
  4. 0, // We do NOT want to remove any item
  5. 'chair', 'Table', 'bed', // These are the items we want to add
  6. );
  7. console.log(foods);

OUTPUT:

 ['rice', 'beans', chair', 'Table', 'bed']

 

That's all about how to append to an array in JavaScript. You have learned 5 ways to achieve this common task, 3 of them are mutative which means they will change the original array, and two of them will return a new array. If you remember, push, splice, and length will mutate the original array. on the other hand, concat and spread will not and will instead return a new array. Which is the best depends on your use case.

Other JavaScript Articles and TutorialsYou May like to explore

Thanks for reading this article so far.  If you like this JavaScript array tutorial and how to check if any includes a value in JavaScript then please share it with your friends and colleagues. If you have any questions or feedback, then, please drop a comment.

P. S. - If you want to learn JavaScript but looking for free resources to learn JavaScript then you can also go through these free JavaScript courses. It has many hands-on free courses to learn modern JavaScript. It contains the best free Javascript courses from Udemy, Coursera, and Pluralsight. 

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.