Using  the Push ()  Method to Manipulate an  Array  In JavaScript

Using the Push () Method to Manipulate an Array In JavaScript

We have different methods to manipulate arrays in JavaScript. We have the Push(), Pop(), Join(), Shift(), Unshift() and many more array methods.

In this article, I would be explaining the Push() method. But before I start, let me remind you of the meaning of an array.

An array is used to hold multiple values and elements. It stores similar items. An example of an array is:

let food = [rice, beans, yam, bread, porridge]

The example above is an array of food. It holds a list of foods. The lists are arranged in index form ( you start counting from 0 from the left to the right side).

For example, rice has an index of 0, the index of beans is 1, yam= 2, bread = 3, and porridge = 4.

Push() Method In JavaScript

The push () method adds one or more elements to the end of an array and returns the new length and new elements.

Steps to add one element to the end of an array include:

On the console tab write:

  1. Write a list of foods in an array. Remember to put them in strings.

    let array = ["bread", "rice", "beans"];

  2. Add a new food "yam" by using the array.push ()

    array.push("yam");

  3. press enter: when you press the enter key the new index of the food list would be displayed. Remember the index started from 0 from the left to the right side.

    new index = 3

  4. Type array and press the enter key again, and the new list of food would be displayed.

    ["bread", "rice", "beans", "yam"]

    If you follow the steps above, you will have the same result in the image below. As you can see, the new item "yam" has been added to the end of the array and a new length has been returned.

    The steps to add two elements to the end of an array are:

    1. Write a list of fruits in an array. Remember to put them in strings.

      let fruits = ["orange", "lemon", "mango"]

    2. Add two fruits to the end of an array using the array.push ()

      array.push("watermelon", "tangerine")

    3. press enter: when you press the enter key the new index of the fruits would be displayed. Remember the index started from 0 from the left to the right side.

      new index = 4

    4. Type array and press the enter key again, and the new list of fruits would be displayed.

      new list = ["orange", "lemon", "mango", "watermelon", "tangerine"].

      If you follow the steps above, you will have the same result in the image below. As you can see, the two fruits "watermelon" and "tangerine" have been added to the end of the array. A new length and list were also returned.

The push () method is very important when you want to add one or more elements to the end of an array. I will explain another method of an array in my next article. I hope you have learned one or two things.