Skip to main content

Command Palette

Search for a command to run...

JavaScript Arrays 101

Updated
•3 min read•View as Markdown

1. What Arrays Are and Why We Need Them

An array is a data structure used to store multiple values in a single variable.
Instead of creating many variables, we can store all values together in an array.

Example without Array

let fruit1 = "Apple";
let fruit2 = "Banana";
let fruit3 = "Mango";

Example with Array

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

Why We Need Arrays

  • To store multiple values in one variable

  • To organize data easily

  • To access and manage values using indexes

  • To loop through data efficiently

💡 Real-life example:
A list of fruits, student marks, or daily tasks.

Diagram Idea

Draw boxes showing array storage:

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

Index:   0        1        2
        -----    -----    -----
        Apple    Banana   Mango
        -----    -----    -----

2. How to Create an Array

Arrays can be created using square brackets [ ].

Example

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

Another example:

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

Diagram idea:

colors
[Red | Green | Blue]
 0      1       2

3. Accessing Elements Using Index

Each element in an array has an index number.

⚠️ Index starts from 0

Example

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

console.log(fruits[0]); // Apple
console.log(fruits[1]); // Banana
console.log(fruits[2]); // Mango

Diagram idea:

fruits

Index:   0        1        2
Value: Apple   Banana   Mango

4. Updating Elements

We can change the value of an array element using its index.

Example

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

fruits[1] = "Orange";

console.log(fruits);

Output:

["Apple", "Orange", "Mango"]

Diagram idea:

Before:

[Apple | Banana | Mango]

After update:

[Apple | Orange | Mango]

5. Array Length Property

The length property tells how many elements are in an array.

Example

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

console.log(fruits.length);

Output:

3

Explanation:
There are 3 elements in the array.


6. Basic Looping Over Arrays

We can use loops to access all elements in an array.

Example using for loop

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

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

Output:

Apple
Banana
Mango

Diagram idea:

Loop → Access each index

i=0 → Apple
i=1 → Banana
i=2 → Mango

Conclusion

Arrays are an important concept in JavaScript that allow us to store and manage multiple values efficiently. They help simplify programs and make data handling easier using indexes, loops, and built-in properties like length.