DEV Community

Nanthini Ammu
Nanthini Ammu

Posted on

JS Arrays

What is an Array?

  • An array is a collection of multiple values stored in a single variable.
  • It is an Object type.
  • List of values known as element.
  • The first element is at index 0, the second at index 1, and so on.
  • Arrays can grow or shrink as elements are added or removed.
  • Arrays can store elements of different data types. So it is Heterogeneous.

Why use Array?

  • Instead of declaring dozens of separate variables for related items (like car1, car2, etc.), they can be grouped into one array.
  • Unlike in many other languages, JavaScript arrays are resizable and can hold a mix of different data types.
  • Arrays make it easy to loop through thousands of items to perform bulk operations.

Creating an Array:

const fruits = ["apple","orange","banan"]

//You can also create an empty array, and provide elements later:

const fruits = [];

fruits[0] = "Apple";
fruits[1] = "Orange";
fruits[2] = "Banana";

//The following example also creates an Array, and assigns values to it:

const fruits = new Array("Apple", "Orange", "Banana");
Enter fullscreen mode Exit fullscreen mode

Accessing Array Elements:

document.write(fruits[0]);
document.write("<br>")
document.write(fruits[1]);
Enter fullscreen mode Exit fullscreen mode

Loop through Array :

Normal :

for(let i =0; i<fruits.length; i++){
    document.write(fruits[i]);
    document.write("<br>");
}

Output:

apple
orange
banan

Enter fullscreen mode Exit fullscreen mode

Using for of :

for(let a of fruits)
{
    document.write(a);
    document.write("<br>");
}

Enter fullscreen mode Exit fullscreen mode

Using forEach :

fruits.forEach(a=> 
{
    document.write(a);
    document.write("<br>");

}
);

----------------------

const numbers = [1,2,3,4,5];

let sum = 0;
numbers.forEach(a=> sum=sum+a);
document.write(sum);


Enter fullscreen mode Exit fullscreen mode

Updating value:

const fruits = ["apple","orange","banan"]

document.write(fruits);
fruits[1] = "grapes";
document.write(fruits);


Output :

apple,orange,banan
apple,grapes,banan

Enter fullscreen mode Exit fullscreen mode

Array Length:

const fruits = ["apple","orange","banan"]

document.write(fruits.length);

Output : 3

Enter fullscreen mode Exit fullscreen mode

pop() :

  • The pop() method removes the last element from an array.
const fruits = ["apple","orange","banan"]

document.write(fruits);
document.write("<br>");
fruits.pop();
document.write(fruits);

Output :

apple,orange,banan
apple,orange

Enter fullscreen mode Exit fullscreen mode

push() :

  • The push() method adds a new element to an array at the end.
const fruits = ["apple","orange","banan"]

document.write(fruits);
document.write("<br>");
fruits.push("papaya");
document.write(fruits);

Output :
apple,orange,banan
apple,orange,banan,papaya

Enter fullscreen mode Exit fullscreen mode

Top comments (0)