Top 5 Array Methods in JavaScript

In javascript array is an collection of set of element which can store in single variable. A Arrays values element always access with their indexes and indexing value always start with 0 means you can stored 5 elements in an array the value will return is 4. You can create array using square brackets[] and separated by (,)comma.operator

Example:- Let cars=[“BMW”,”AUDI”,”G-WAGON”]

Top 5 Array Method in JavaScript

1. length()

In javascript length() method is used to count the length of an array and return a numeric value.

It is a built-in method that provides the number of an element in an array This method are always use with (.) operator

Syntax:

const arrayname= [“val1”, “val2”, “val3”, “val4”];
console.log(arrayname.length);

Example
const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];
console.log(fruits.length);
Output:-4

2. toString()

In javascript toString()method is used to convert array to string of array elements separated by (,) commas.This method does not take any parameters and return the output in (“ ”) double quotes thats consider as a string.

Syntax:

let arrayname= [num1,num2];

let arrayString = arrayname.toString();

console.log(arrayString);

Example
const array = [1, 2, 3, 4, 5];

const arrayString = array.toString();

console.log(arrayString);

Output: “1,2,3,4,5”

3. pop()

In JavaScript, the Array.pop() method is used to remove the last element from an array and returns that element. This method modifies the array directly, reducing its length at the last of index value.

Syntax:

const arrayname = [“val2”, “val2”];

arrayname .pop();

Example

const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];

fruits.pop();

Output: mango

4. push()

In JavaScript, the Array.push() method is used to add one or more elements to the end of an array and returns the new length of the array after adding the elements.

Syntax:

Const arrayname = [“val1”,”val2”];

arrayname.push(“new val”);

Example

const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];

fruits.push(“Kiwi”, “Lemon”);

Output: Banana,Orange,Apple,Mango,Kiwi,Lemon

5. array.sort()

In javascript sort() method is used to sorting the element of an array. By default, sort() method converts elements to strings and sorts them based on their code units and sort number in ascending order.

Syntax:

const arrayname = [“val1”,”val2”,val3];

arrayname.sort();

Example

const fruits = [“Banana”, “Orange”, “Apple”, “Mango”];

fruits.sort();

output: Apple,Banana,Mango,Orange

Output: Banana,Orange,Apple,Mango,Kiwi,Lemon

1 thought on “Top 5 Array Methods in JavaScript”

Leave a Comment