`

Arrays

What is an Array?

Imagine you have a row of lockers, each with a number on it, and inside each locker, you store something (books, clothes, snacks, etc.). This row of lockers is just like an array in programming—a collection of items stored in a fixed, ordered sequence.

An array is a container that holds multiple values of the same type. Instead of using separate variables for each item, you can store them together in an array.

Example:

Let's say we want to store five numbers:

Instead of writing:

let num1 = 10;
let num2 = 20;
let num3 = 30;
let num4 = 40;
let num5 = 50;

We can store all of them in an array:

let numbers = [10, 20, 30, 40, 50];

Now, all five values are stored neatly in the `numbers` array!

How to Access Elements in an Array?

Arrays use index numbers to access their elements. Think of index numbers like locker numbers—they help you find and retrieve the stored items.

Example:

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

In arrays, indexing starts from 0, so:

- `fruits[0]` refers to "Apple"

- `fruits[1]` refers to "Banana"

- `fruits[2]` refers to "Cherry"

- `fruits[3]` refers to "Mango"

Adding and Removing Items in an Array

Arrays are flexible! You can add and remove items dynamically.

Adding an item:

Use `.push()` to add an item at the end of the array:

let colors = ["Red", "Blue", "Green"];
colors.push("Yellow");
console.log(colors); // Output: ["Red", "Blue", "Green", "Yellow"]


Removing an item:

Use `.pop()` to remove the last item:
colors.pop();
console.log(colors); // Output: ["Red", "Blue", "Green"]


Looping Through an Array

You often need to loop through arrays to access each element.

Using a `for` loop:

let cities = ["New York", "Tokyo", "London", "Paris"];
for (let i = 0; i < cities.length; i++) {
console.log(cities[i]);
}

This will print all city names one by one.

Using `.forEach()` (simpler way):

cities.forEach(city => console.log(city));

Both approaches give the same result!


Why Use Arrays?

Arrays make coding **easier and efficient** because:

- They store **multiple values** in one variable.

- They allow **easy access** using indexes.

- They provide **built-in methods** for adding, removing, and searching items.

- They work **fast and efficiently** in programs.


Published :