What Are JavaScript Arrays? See Examples in detail

Arrays are one of the most commonly used data structures in JavaScript. They allow you to store multiple values in a single variable, making it easier to manage and manipulate data efficiently.

This blog will explain arrays, how to use them, and provide practical examples.


1. What Is an Array?

An array is an ordered collection of values. Each value has an index, starting from 0.

Example:

let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits[0]); // Apple
console.log(fruits[2]); // Mango

2. Creating Arrays

Using Square Brackets

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

Using Array Constructor

let colors = new Array("Red", "Green", "Blue");

3. Array Properties

Length

The .length property returns the number of elements.

let fruits = ["Apple", "Banana", "Mango"];
console.log(fruits.length); // 3

4. Common Array Methods

Add Elements

let fruits = ["Apple", "Banana"];
fruits.push("Mango");  // Add at end
fruits.unshift("Orange"); // Add at start
console.log(fruits); // ["Orange","Apple","Banana","Mango"]

Remove Elements

fruits.pop();   // Remove from end
fruits.shift(); // Remove from start

Find Elements

console.log(fruits.indexOf("Banana")); // 1
console.log(fruits.includes("Apple")); // true

5. Looping Through Arrays

For Loop

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

forEach Method

fruits.forEach(function(item){
  console.log(item);
});

for…of Loop

for(let fruit of fruits){
  console.log(fruit);
}

6. Multi-Dimensional Arrays

Arrays can contain other arrays (2D, 3D arrays).

Example

let matrix = [
  [1,2,3],
  [4,5,6],
  [7,8,9]
];
console.log(matrix[1][2]); // 6

7. Array Destructuring (ES6)

Easily extract values into variables.

let [first, second] = ["Apple", "Banana"];
console.log(first);  // Apple
console.log(second); // Banana

Conclusion

Arrays are powerful structures in JavaScript that allow you to store, manage, and manipulate collections of data efficiently. Mastering arrays and their methods is essential for any JavaScript developer.


📌 Citations

🔗 View other articles about Javascript:
https://savanka.com/category/learn/js/

🔗 External Javascript Documentation:
https://www.w3schools.com/js/

Leave a Comment

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *