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:
We can store all of them in an array:
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:
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:
Removing an item:
Looping Through an Array
You often need to loop through arrays to access each element.
Using a `for` loop:
This will print all city names one by one.
Using `.forEach()` (simpler way):
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 :