DEV Community

subash
subash

Posted on

Understanding Arrays: A Beginner-Friendly Explanation (With Examples)

What is an Array?

An array is a collection of items stored in a single variable.

Think about a box of fruits πŸŽπŸŒπŸ‡
Instead of storing each fruit in a separate variable, we store all in one array.

Example without Array
let fruit1 = "Apple";
let fruit2 = "Banana";
let fruit3 = "Mango";

❌ Problem: Too many variables

Example with Array
let fruits = ["Apple", "Banana", "Mango"];

βœ… Easy and clean!

Index Concept (Important)

Array starts from index 0.

How does it work?

To keep things organized, an array gives every item a number. This number is called an Index.

The Golden Rule: In the world of computers, we always start counting from 0, not 1.

So, the first item is at position 0, the second is at 1, and the third is at 2.

Enter fullscreen mode Exit fullscreen mode




Homogeneous (The Same Type)

Usually, an array likes to hold the same kind of things. If it’s a list of names, keep it all names. If it’s a list of numbers, keep it all numbers.
Contiguous (All Together)

In the computer's memory, the items in an array sit right next to each other in a perfect row. There are no gaps or empty spaces between them.

Fixed vs. Dynamic Size

Fixed Size: Some languages require you to decide the size of the list at the start. You cannot add more later.

Dynamic Size: Modern languages (like JavaScript) let the list grow as long as you want!

Enter fullscreen mode Exit fullscreen mode




ADDING VALUES;

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

fruits.push("Mango");

console.log(fruits);

Adds value to end

REMOVING VALUES

fruits.pop();

Removes last value

LOOPING ARRAY

let fruits = ["Apple", "Banana", "Mango"];

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

Prints all values

FOR LOOP

=> This is for loop first condition let i = 0 is what the i value while start
=> second condition is i < fruits.length , in this case fruits length is 3, so it will consider that condition as i<3, this condition is for to limit the loop, the loop is run only less than 3, but index start with 0 , so we have space to fit three value in this loop.
=> third condition how the i will increase , i want to increase like 2 4 6 then put i+=2 instead of i++;

Why Arrays are Important?

Array is a powerful and simple way to store multiple values in one place.
Easy to manage data
Used in almost all programs
Arrays can store any type (number, string, object)

Top comments (0)