DEV Community

Cover image for JavaScript Arrays 101
Pratham
Pratham

Posted on

JavaScript Arrays 101

Your first real data structure — and the one you'll use more than any other.


Let me paint a picture. You're building a to-do app. You've got 5 tasks. So you do the "logical" thing:

let task1 = "Buy groceries";
let task2 = "Finish homework";
let task3 = "Call mom";
let task4 = "Go to gym";
let task5 = "Read a chapter";
Enter fullscreen mode Exit fullscreen mode

Five variables for five tasks. Now imagine you have 50 tasks. Or 500. Are you going to create 500 separate variables? Obviously not. That's insane. And even with just 5, how do you loop through them? How do you add a new one? How do you remove one?

This is exactly the problem arrays solve. And once you get comfortable with them, you'll wonder how you ever wrote JavaScript without them.


What Is an Array?

An array is an ordered collection of values stored under a single variable name. Instead of creating a separate variable for each value, you put them all in one place — like a numbered list.

Think of it as a row of lockers. Each locker has a number (its index) and can hold one item (a value). You can look at any locker, change what's inside, or walk down the entire row checking each one.

┌─────────┬─────────┬─────────┬─────────┬─────────┐
│  Index 0│  Index 1│  Index 2│  Index 3│  Index 4│
├─────────┼─────────┼─────────┼─────────┼─────────┤
│ "Buy    │ "Finish │ "Call   │ "Go to  │ "Read a │
│ grocer- │ home-   │  mom"   │  gym"   │ chapter"│
│  ies"   │  work"  │         │         │         │
└─────────┴─────────┴─────────┴─────────┴─────────┘
Enter fullscreen mode Exit fullscreen mode

One variable. Five values. Organized, indexed, and easy to work with.


Why Do We Need Arrays?

Let's compare the two approaches directly:

Without Arrays — A Variable for Each Value

let fruit1 = "Apple";
let fruit2 = "Mango";
let fruit3 = "Banana";
let fruit4 = "Grapes";
let fruit5 = "Orange";

console.log(fruit1);
console.log(fruit2);
console.log(fruit3);
console.log(fruit4);
console.log(fruit5);
Enter fullscreen mode Exit fullscreen mode

Five variables. Five console.log calls. And if you want to add a sixth fruit? Create another variable, add another log. It doesn't scale.

With an Array — One Variable, All Values

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

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

One variable. One loop. Add 50 more fruits and the loop still works without changing a single line. That's the power of arrays.


How to Create an Array

Creating an array in JavaScript is simple. You use square brackets [] and separate the values with commas.

Syntax

let arrayName = [value1, value2, value3, ...];
Enter fullscreen mode Exit fullscreen mode

Examples

// Array of strings
let cities = ["Delhi", "Mumbai", "Bangalore", "Gurugram"];

// Array of numbers
let marks = [85, 92, 78, 95, 88];

// Array of booleans
let answers = [true, false, true, true, false];

// Mixed array (JavaScript allows this — but use it sparingly)
let mixed = ["Pratham", 22, true, null];

// Empty array (you'll fill it later)
let todoList = [];
Enter fullscreen mode Exit fullscreen mode

JavaScript arrays are flexible — they can hold any data type, and you can even mix types in a single array. That said, in real-world code, you'll almost always keep arrays to one type for consistency and readability.


Accessing Elements Using Index

Every item in an array has a position called its index. And here's the thing that trips up every single beginner:

Array indexing starts at 0, not 1.

The first element is at index 0, the second at index 1, and so on.

Visual: How Indexing Works

Array:   ["Delhi", "Mumbai", "Bangalore", "Gurugram"]
Index:       0         1          2            3
Enter fullscreen mode Exit fullscreen mode

Accessing Elements

let cities = ["Delhi", "Mumbai", "Bangalore", "Gurugram"];

console.log(cities[0]); // "Delhi"      — first element
console.log(cities[1]); // "Mumbai"     — second element
console.log(cities[2]); // "Bangalore"  — third element
console.log(cities[3]); // "Gurugram"   — fourth (last) element
Enter fullscreen mode Exit fullscreen mode

What Happens If You Use an Invalid Index?

console.log(cities[10]); // undefined — no error, just undefined
console.log(cities[-1]); // undefined — negative indexes don't work like Python
Enter fullscreen mode Exit fullscreen mode

JavaScript won't throw an error. It'll just quietly return undefined. Keep this in mind — it can cause silent bugs if you're not careful.

Accessing the Last Element

A common pattern you'll use all the time:

let cities = ["Delhi", "Mumbai", "Bangalore", "Gurugram"];

let lastCity = cities[cities.length - 1];
console.log(lastCity); // "Gurugram"
Enter fullscreen mode Exit fullscreen mode

Why cities.length - 1? Because if there are 4 elements, the last index is 3 (remember, we start at 0). So length - 1 always gives you the last index.


Updating Elements

Changing a value in an array is as simple as assigning a new value to a specific index.

let fruits = ["Apple", "Mango", "Banana", "Grapes"];
console.log(fruits); // ["Apple", "Mango", "Banana", "Grapes"]

// Let's say I changed my mind about Banana
fruits[2] = "Strawberry";
console.log(fruits); // ["Apple", "Mango", "Strawberry", "Grapes"]
Enter fullscreen mode Exit fullscreen mode

You just point to the index and overwrite the value. The array updates in place — you don't need to create a new one.

A Practical Example

let scores = [70, 85, 60, 90, 75];

// Student at index 2 retook the exam and improved
scores[2] = 82;

console.log(scores); // [70, 85, 82, 90, 75]
Enter fullscreen mode Exit fullscreen mode

Adding to the End (Quick Preview)

You can also add new elements beyond the current length:

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

colors[2] = "Green"; // Adding at index 2
console.log(colors); // ["Red", "Blue", "Green"]
Enter fullscreen mode Exit fullscreen mode

But be careful — if you skip an index:

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

colors[5] = "Green"; // Skipping indexes 2, 3, 4
console.log(colors); // ["Red", "Blue", empty × 3, "Green"]
console.log(colors.length); // 6 — includes the empty slots!
Enter fullscreen mode Exit fullscreen mode

This creates "holes" in your array with empty slots. Don't do this intentionally — it leads to unexpected behavior.


The length Property

Every array has a built-in length property that tells you how many elements it contains.

let movies = ["Inception", "Interstellar", "The Dark Knight", "Tenet"];

console.log(movies.length); // 4
Enter fullscreen mode Exit fullscreen mode

Why Is length Useful?

You'll use it constantly:

  • Finding the last element: array[array.length - 1]
  • Looping through arrays: as the upper bound for your loop
  • Checking if an array is empty: array.length === 0
let tasks = [];

if (tasks.length === 0) {
  console.log("No tasks! You're free. 🎉");
}
// Output: "No tasks! You're free. 🎉"
Enter fullscreen mode Exit fullscreen mode

Important: length Is Not the Last Index

This is a subtle but important distinction:

Array:   ["A", "B", "C", "D"]
Indexes:   0    1    2    3
Length:  4

Last index = length - 1 = 3 ✅
Last index ≠ length = 4 ❌ (this would be out of bounds)
Enter fullscreen mode Exit fullscreen mode

I've seen this cause off-by-one errors more times than I can count. Remember: last index = length minus 1.


Looping Over Arrays

This is where arrays start to shine. The ability to process every element with a loop is what makes arrays so powerful.

1. The Classic for Loop

The most fundamental way to iterate through an array:

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

for (let i = 0; i < fruits.length; i++) {
  console.log(i + ": " + fruits[i]);
}
// 0: Apple
// 1: Mango
// 2: Banana
// 3: Grapes
// 4: Orange
Enter fullscreen mode Exit fullscreen mode

Let me break this down:

  • let i = 0 — start at the first index
  • i < fruits.length — keep going as long as i is less than the total count
  • i++ — move to the next index after each iteration
  • fruits[i] — access the element at the current index

2. The for...of Loop (Cleaner Syntax)

If you don't need the index and just want the values, for...of is cleaner:

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

for (let fruit of fruits) {
  console.log(fruit);
}
// Apple
// Mango
// Banana
// Grapes
// Orange
Enter fullscreen mode Exit fullscreen mode

No index tracking, no length check — just the values, one at a time. I use this whenever I don't need to know which position the element is at.

3. The while Loop (Less Common for Arrays)

You can use a while loop too, though it's less common for simple iteration:

let fruits = ["Apple", "Mango", "Banana", "Grapes", "Orange"];
let i = 0;

while (i < fruits.length) {
  console.log(fruits[i]);
  i++;
}
Enter fullscreen mode Exit fullscreen mode

Same result, just a different way to structure the loop. I'd stick with for or for...of for arrays — they're more readable and less prone to accidentally creating infinite loops.

When to Use Which Loop

Loop When to Use
for When you need the index or want full control
for...of When you just want the values — cleanest syntax
while When the stopping condition isn't index-based

Memory-Style Block Diagram

Here's how you can think about an array stored in memory — each block has an index and a value:

Variable: fruits
    │
    ▼
┌────────────────────────────────────────────────────────────┐
│                     Array in Memory                        │
├──────────┬──────────┬──────────┬──────────┬────────────────┤
│ [0]      │ [1]      │ [2]      │ [3]      │ [4]           │
│ "Apple"  │ "Mango"  │ "Banana" │ "Grapes" │ "Orange"      │
├──────────┴──────────┴──────────┴──────────┴────────────────┤
│ length: 5                                                  │
└────────────────────────────────────────────────────────────┘

Accessing: fruits[2]  →  goes to block [2]  →  returns "Banana"
Updating:  fruits[3] = "Kiwi"  →  block [3] changes from "Grapes" to "Kiwi"
Enter fullscreen mode Exit fullscreen mode

The key insight: array elements are stored contiguously (next to each other) and accessed by index — which makes looking up any element fast regardless of the array size.


Let's Practice: Hands-On Assignment

Part 1: Create an Array of 5 Favorite Movies

let movies = [
  "Inception",
  "Interstellar",
  "The Dark Knight",
  "Dangal",
  "3 Idiots"
];

console.log(movies);
// ["Inception", "Interstellar", "The Dark Knight", "Dangal", "3 Idiots"]
Enter fullscreen mode Exit fullscreen mode

Part 2: Print the First and Last Element

console.log("First movie:", movies[0]);
// First movie: Inception

console.log("Last movie:", movies[movies.length - 1]);
// Last movie: 3 Idiots
Enter fullscreen mode Exit fullscreen mode

Part 3: Change One Value and Print the Updated Array

// I changed my mind — replacing "Dangal" with "Oppenheimer"
movies[3] = "Oppenheimer";

console.log("Updated array:", movies);
// Updated array: ["Inception", "Interstellar", "The Dark Knight", "Oppenheimer", "3 Idiots"]
Enter fullscreen mode Exit fullscreen mode

Part 4: Loop Through the Array and Print All Elements

console.log("--- My Favorite Movies ---");

for (let i = 0; i < movies.length; i++) {
  console.log((i + 1) + ". " + movies[i]);
}
// 1. Inception
// 2. Interstellar
// 3. The Dark Knight
// 4. Oppenheimer
// 5. 3 Idiots
Enter fullscreen mode Exit fullscreen mode

Or with a for...of loop:

console.log("--- Movie List ---");

for (let movie of movies) {
  console.log("🎬 " + movie);
}
// 🎬 Inception
// 🎬 Interstellar
// 🎬 The Dark Knight
// 🎬 Oppenheimer
// 🎬 3 Idiots
Enter fullscreen mode Exit fullscreen mode

Key Takeaways

  1. Arrays are ordered collections of values stored in a single variable. They solve the problem of managing multiple related values without creating separate variables for each.
  2. Indexing starts at 0. The first element is array[0], not array[1]. The last element is always array[array.length - 1].
  3. Updating is simple — just assign a new value to a specific index: array[index] = newValue.
  4. The length property tells you how many elements the array contains. It's not the same as the last index (length - 1 is).
  5. Loops are how you process every element in an array. Use for when you need the index, for...of when you just want the values.

Wrapping Up

Arrays are probably the single most important data structure you'll work with in JavaScript. Every real project I've seen — from e-commerce product lists to social media feeds to to-do apps — uses arrays under the hood. Getting comfortable with creating, accessing, updating, and looping through them is foundational to everything that comes next: array methods, objects, APIs, and beyond.

I'm working through all of this in the ChaiCode Web Dev Cohort 2026 under Hitesh Chaudhary and Piyush Garg, and I have to say — arrays were the first topic where I started feeling like I could actually build things, not just learn theory.

If this helped you, feel free to connect with me on LinkedIn or check out PrathamDEV.in. I'll keep writing as I keep learning — next up, array methods and objects.

Happy coding! 🚀


Written by Pratham Bhardwaj | Web Dev Cohort 2026, ChaiCode

Top comments (0)