You are currently viewing Javascript Array Methods With Examples | Explained

Javascript Array Methods With Examples | Explained

Javascript Array Methods With Examples

This article is about javascript array methods with examples.

What is an array?

The array is a collection of data elements (or data values). Arrays are created to store multiple values in a single variable. If you want to store multiple values or a list of values in a single variable then you create a variable of type array.

Creating a variable of type array

using literal notation

Syntax:

var arrayname = [comma separated list of values];

Ex:

//Creating an Array:
var studnames = ["ram", "ravi", "raju", "ragu"];

//Displaying an Array:
document.write(studName); //Output : ram, ravi, raju, ragu

//Displaying length of an array:
document.write(studName.length); // Output : 4

Array Methods

There are two important methods in an array are push() and Pop()

Push() Method

  1. It adds one or more elements to the end of the array.
  2. And returns the new length of the array

Syntax:

push(..args):number

where:

  • args = indicates one or more elements
  • number = indicates new length of the array

Example:

var studnames = ["ram", "ravi", "raju", "ragu"];
document.write(studnames.push("rakesh"));
//output : 5

In the above code, we have created an array with 4 values. I want to add one more value to the array, so I use push() method and give values as “rakesh”. The push method add the “rakesh” to the end of the array “studnames”, when “rakesh” value is added total elements will be 5. So, it returns the length of an array 5. Whenever you want to add an element to the end of the array, you will be taking the help of the push() method.

pop() Method

  1. Pop removes the element at the end of the array
  2. And returns that end of the elements
READ ALSO  How to Get User Input in JavaScript | Explained

Syntax:

pop():*

where:

  • * = indicates element at the end of the array

Example:

var studnames = ["ram", "ravi", "raju", "ragu"];
document.write(studnames.pop());
// output : ragu

In the above code, we have an array with 4 values. I want to remove the end of the array element, So I use pop() method. Here I use the document.write() method for displaying and then write array name “studnames” then I use pop() method without passing any arguments. So, The pop() method removes the end of the element “ragu” and returns the end element “ragu”.

Leave a Reply