DEV Community

Alaguselvan T
Alaguselvan T

Posted on

ARRAY IN JS

Definition
An array is an ordered collection of values stored in a single variable. Each value in an array is called an element, and every element has an index. Array indexing starts at 0.

const fruits = ["Apple", "Banana", "Orange"];

console.log(fruits);
Enter fullscreen mode Exit fullscreen mode

Why Do We Use Arrays?
Without arrays, you would need multiple variables to store similar data.

Accessing Array Elements:
Access elements using their index.

const fruits = ["Apple", "Banana", "Orange"];

console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);
Enter fullscreen mode Exit fullscreen mode

Modifying Array Elements
You can update an element by assigning a new value to its index.

const fruits = ["Apple", "Banana", "Orange"];

fruits[1] = "Mango";

console.log(fruits);
Enter fullscreen mode Exit fullscreen mode

Finding the Length of an Array
Use the length property.

const fruits = ["Apple", "Banana", "Orange"];

console.log(fruits.length);
Enter fullscreen mode Exit fullscreen mode

Adding Elements
push()
Adds an element to the end of the array.

const fruits = ["Apple", "Banana"];

fruits.push("Orange");

console.log(fruits);
Enter fullscreen mode Exit fullscreen mode

unshift()
Adds an element to the beginning.

const fruits = ["Banana", "Orange"];

fruits.unshift("Apple");

console.log(fruits);
Enter fullscreen mode Exit fullscreen mode

Removing Elements
pop()
Removes the last element.

const fruits = ["Apple", "Banana", "Orange"];

fruits.pop();

console.log(fruits);
Enter fullscreen mode Exit fullscreen mode

shift()
Removes the first element.

const fruits = ["Apple", "Banana", "Orange"];

fruits.shift();

console.log(fruits);
Enter fullscreen mode Exit fullscreen mode

Looping Through Arrays
Using a for Loop

const fruits = ["Apple", "Banana", "Orange"];

for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}
Enter fullscreen mode Exit fullscreen mode

Using for...of

const fruits = ["Apple", "Banana", "Orange"];

for (const fruit of fruits) {
  console.log(fruit);
}
Enter fullscreen mode Exit fullscreen mode

Using foreach();(TBD)

const fruits = ["Apple", "Banana", "Orange"];

fruits.forEach((fruit) => {
  console.log(fruit);
});
Enter fullscreen mode Exit fullscreen mode

Top comments (0)