Arrays in JavaScript โ€“ concepts, types and usage.

Arrays in JavaScript โ€“ concepts, types and usage. iti

๐Ÿ“š Arrays in JavaScript โ€“ Concepts, Types and Usage

An Array in JavaScript is a special type of object used to store multiple values in a single variable. Instead of declaring separate variables for each value, you can group them in an array for easier access and management. Arrays are commonly used in web development to store and manipulate lists of data.


๐Ÿ” What is an Array?

A JavaScript array is a collection of elements (values), each with a numeric index starting from 0.

let fruits = ["Apple", "Banana", "Mango"];
  • fruits[0] returns "Apple"
  • fruits[1] returns "Banana"
  • fruits[2] returns "Mango"

๐Ÿ“Œ How to Declare an Array?

โœ… Using Array Literal (Preferred):

let colors = ["Red", "Green", "Blue"];

โœ… Using Array Constructor:

let numbers = new Array(10, 20, 30);

๐Ÿงช Types of Arrays in JavaScript

Though all arrays in JavaScript are of the same base type, we can classify them based on usage:

1. Homogeneous Arrays (Same data type)

let scores = [90, 80, 70];

2. Heterogeneous Arrays (Mixed data types)

let info = ["John", 25, true];

3. Multidimensional Arrays

let matrix = [
  [1, 2],
  [3, 4]
];

๐Ÿ› ๏ธ Common Array Methods

MethodDescriptionExample
push()Adds element at endarr.push("New")
pop()Removes last elementarr.pop()
shift()Removes first elementarr.shift()
unshift()Adds element at startarr.unshift("Start")
lengthGives array sizearr.length
indexOf()Finds index of itemarr.indexOf("item")
includes()Checks if item existsarr.includes("Apple")
join()Joins all elementsarr.join(", ")
reverse()Reverses orderarr.reverse()

๐Ÿ”„ Looping through an Array

โœ… Using for loop:

let fruits = ["Apple", "Banana", "Mango"];
for (let i = 0; i < fruits.length; i++) {
  console.log(fruits[i]);
}

โœ… Using forEach method:

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

๐ŸŽฏ Array Use Cases

  • Storing user data (like names, scores, preferences)
  • Managing dynamic lists (shopping cart, todo list)
  • Form validations and batch data processing
  • Real-time data updates in web applications

๐Ÿ“Œ Summary

  • Arrays store multiple values in a single variable.
  • They are indexed from 0.
  • Support various methods to add, remove, and manipulate data.
  • Useful for looping and batch operations.

JavaScript arrays are extremely versatile and form the backbone of dynamic data management in modern web development. ๐Ÿš€