← Back to course

Arrays

Arrays

Welcome back.

In the previous lesson, you learned functions.

Functions help you reuse code, organize logic, and avoid copy-paste soup.

Very useful.

Very civilized.

Today we move to another important idea in JavaScript.

Arrays.

An array is a list of values.

Instead of creating many separate variables, you can store many values inside one variable.

Without arrays, your code becomes this:

const student1 = "Anna";
const student2 = "Marco";
const student3 = "Luca";
const student4 = "Sofia";

This works.

But it is not beautiful.

It is like carrying one potato in each pocket instead of using a bag.

With arrays, we can write:

const students = ["Anna", "Marco", "Luca", "Sofia"];

Much better.

One variable.

Many values.

Less chaos.

JavaScript is slowly learning how to organize its room.

Almost.

What You Will Learn

In this lesson, you will learn:

By the end of this lesson, you will understand how JavaScript stores lists of data.

This is a big step.

Because real websites are full of lists.

Products.

Users.

Blog posts.

Menu items.

Comments.

Tasks.

Photos.

Everything is a list if you stare at it long enough.

Slightly philosophical.

Still JavaScript.

What Is an Array?

An array is a special variable that can store multiple values.

Example:

const fruits = ["apple", "banana", "orange"];

Here we have one variable:

fruits

Inside it, we have three values:

apple
banana
orange

An array uses square brackets:

[]

Each value is separated by a comma.

Example:

const numbers = [10, 20, 30, 40];
const names = ["Anna", "Marco", "Viktor"];
const mixed = ["JavaScript", 2026, true];

An array can contain strings, numbers, booleans, and other values.

But usually, we keep similar data together.

Like this:

const products = ["Laptop", "Mouse", "Keyboard"];

Not like this:

const strangeArray = ["Pizza", 42, false, "A confused penguin"];

JavaScript allows it.

But just because you can do something does not mean you should.

Very important life lesson.

Also programming lesson.

Create the Project

Create a folder for this lesson:

mkdir javascript-lesson5
cd javascript-lesson5
touch index.html
touch script.js

Your project should look like this:

javascript-lesson5/
  index.html
  script.js

Open the folder in your editor.

We will start in the console.

Then we will use arrays to update a web page.

No framework dragon today.

Only JavaScript.

Still dangerous.

But manageable.

Write the HTML

Open index.html and add this:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Arrays</title>
</head>
<body>
  <h1>Arrays</h1>
  <p>Open the browser console to see JavaScript output.</p>

  <script src="script.js"></script>
</body>
</html>

Open the file in your browser.

Open the console:

Now JavaScript is ready.

The console is watching.

Again.

It never sleeps.

Your First Array

Open script.js and add:

const fruits = ["apple", "banana", "orange"];

console.log(fruits);

Refresh the browser.

You should see:

["apple", "banana", "orange"]

Congratulations.

You created your first array.

It may look simple.

But this little thing is one of the most important tools in JavaScript.

A variable stores one value.

An array stores many values.

That is the difference.

Small brackets.

Big power.

Array Indexes

Every item in an array has a position.

This position is called an index.

Important:

JavaScript starts counting from zero.

Not from one.

From zero.

Because programmers looked at normal counting and said:

“No. Too comfortable.”

Example:

const fruits = ["apple", "banana", "orange"];

console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);

Output:

apple
banana
orange

Here is the structure:

Index 0 -> apple
Index 1 -> banana
Index 2 -> orange

So the first item is:

fruits[0]

Not:

fruits[1]

This is one of the most common beginner mistakes.

Do not worry.

Everyone makes it.

Then everyone suffers.

Then everyone remembers.

This is the natural path of JavaScript wisdom.

Accessing Array Items

You can access any item using its index.

Example:

const languages = ["HTML", "CSS", "JavaScript"];

console.log(languages[0]);
console.log(languages[1]);
console.log(languages[2]);

Output:

HTML
CSS
JavaScript

If you try to access an index that does not exist:

console.log(languages[5]);

Output:

undefined

Why?

Because there is no item at index 5.

JavaScript does not panic.

It simply says:

undefined

Which means:

“I found nothing here, my friend.”

Very calm.

Almost suspiciously calm.

Changing Array Items

You can change an item in an array.

Example:

const fruits = ["apple", "banana", "orange"];

fruits[1] = "kiwi";

console.log(fruits);

Output:

["apple", "kiwi", "orange"]

The item at index 1 was changed.

Before:

banana

After:

kiwi

The banana has left the building.

No explanation.

No goodbye.

Just JavaScript.

Adding Items with push

To add an item to the end of an array, use push.

Example:

const fruits = ["apple", "banana"];

fruits.push("orange");

console.log(fruits);

Output:

["apple", "banana", "orange"]

push adds a new item at the end.

Another example:

const tasks = ["study JavaScript", "drink coffee"];

tasks.push("build a website");

console.log(tasks);

Output:

["study JavaScript", "drink coffee", "build a website"]

This is useful when the user adds something.

A new task.

A new product.

A new message.

A new problem.

Especially the last one.

Web development loves new problems.

Removing Items with pop

To remove the last item from an array, use pop.

Example:

const fruits = ["apple", "banana", "orange"];

fruits.pop();

console.log(fruits);

Output:

["apple", "banana"]

pop removes the last item.

It can also return the removed item:

const fruits = ["apple", "banana", "orange"];

const removedFruit = fruits.pop();

console.log(removedFruit);
console.log(fruits);

Output:

orange
["apple", "banana"]

The orange was removed.

But we saved it in a variable.

Very dramatic.

Very organized.

Array Length

To check how many items are inside an array, use .length.

Example:

const fruits = ["apple", "banana", "orange"];

console.log(fruits.length);

Output:

3

This tells us the array has three items.

Another example:

const students = ["Anna", "Marco", "Luca", "Sofia"];

console.log(`There are ${students.length} students.`);

Output:

There are 4 students.

.length is very useful.

Especially when we need to loop through arrays.

And yes.

Loops are coming.

Do not run away.

They are friendly.

Mostly.

Looping Through an Array

Imagine we have this array:

const fruits = ["apple", "banana", "orange"];

We could print each item manually:

console.log(fruits[0]);
console.log(fruits[1]);
console.log(fruits[2]);

This works.

But it is not flexible.

What if we have 100 items?

Are we going to write 100 console.log lines?

No.

We have dignity.

We use a loop.

Example:

const fruits = ["apple", "banana", "orange"];

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

Output:

apple
banana
orange

How does it work?

let i = 0

Start from index 0.

i < fruits.length

Continue while i is smaller than the array length.

i++

Increase i after every loop.

Then:

fruits[i]

gets the current item.

This is a very common pattern in JavaScript.

You will see it everywhere.

Like dust.

But useful dust.

The for...of Loop

There is also an easier way to loop through arrays.

Example:

const fruits = ["apple", "banana", "orange"];

for (const fruit of fruits) {
  console.log(fruit);
}

Output:

apple
banana
orange

This is called a for...of loop.

It is clean and easy to read.

Use it when you want to get each item directly.

Example:

const names = ["Anna", "Marco", "Viktor"];

for (const name of names) {
  console.log(`Hello, ${name}!`);
}

Output:

Hello, Anna!
Hello, Marco!
Hello, Viktor!

Very nice.

Very readable.

No index drama.

for Loop vs for...of

Use a normal for loop when you need the index.

Example:

const products = ["Laptop", "Mouse", "Keyboard"];

for (let i = 0; i < products.length; i++) {
  console.log(`${i}: ${products[i]}`);
}

Output:

0: Laptop
1: Mouse
2: Keyboard

Use for...of when you only need the value.

Example:

const products = ["Laptop", "Mouse", "Keyboard"];

for (const product of products) {
  console.log(product);
}

Output:

Laptop
Mouse
Keyboard

Simple rule:

If you need the index, use for.

If you only need the item, use for...of.

JavaScript gives you choices.

Sometimes too many.

But these two are useful.

Arrays and Conditions

You can use conditions inside loops.

Example:

const prices = [10, 25, 50, 5, 100];

for (const price of prices) {
  if (price > 20) {
    console.log(`Expensive item: €${price}`);
  }
}

Output:

Expensive item: €25
Expensive item: €50
Expensive item: €100

This is powerful.

You can filter data.

You can find important items.

You can check rules.

Example:

const ages = [12, 18, 25, 16, 40];

for (const age of ages) {
  if (age >= 18) {
    console.log(`${age} can enter.`);
  } else {
    console.log(`${age} cannot enter.`);
  }
}

Output:

12 cannot enter.
18 can enter.
25 can enter.
16 cannot enter.
40 can enter.

Arrays store the data.

Loops go through the data.

Conditions make decisions.

Now JavaScript is becoming a small office worker.

A little tired.

But productive.

Arrays and Functions

Arrays work very well with functions.

Example:

function showProducts(products) {
  for (const product of products) {
    console.log(product);
  }
}

const products = ["Laptop", "Mouse", "Keyboard"];

showProducts(products);

Output:

Laptop
Mouse
Keyboard

Here the function receives an array.

Then it loops through it.

This is very common in real projects.

Another example:

function countItems(items) {
  return items.length;
}

const tasks = ["study", "practice", "build"];

console.log(countItems(tasks));

Output:

3

Functions and arrays are good friends.

Functions do actions.

Arrays hold data.

Together they are dangerous.

In a good way.

Mostly.

Build a Task List

Now let us build a small page that displays a list of tasks.

Update index.html:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Arrays</title>

  <style>
    body {
      font-family: Arial, sans-serif;
      max-width: 700px;
      margin: 60px auto;
      padding: 0 24px;
      background-color: #f3f4f6;
      color: #111827;
    }

    .card {
      background-color: white;
      padding: 24px;
      border: 2px solid #e5e7eb;
      border-radius: 18px;
    }

    h1 {
      font-size: 42px;
    }

    p,
    li {
      font-size: 20px;
      line-height: 1.6;
    }

    ul {
      padding-left: 24px;
    }

    li {
      margin-bottom: 10px;
    }

    .count {
      font-weight: 700;
      color: #2563eb;
    }
  </style>
</head>
<body>
  <h1>Arrays</h1>

  <div class="card">
    <h2>Today&apos;s Tasks</h2>
    <p id="taskCount" class="count"></p>
    <ul id="taskList"></ul>
  </div>

  <script src="script.js"></script>
</body>
</html>

Now update script.js:

const tasks = [
  "Learn arrays",
  "Practice loops",
  "Build a small project",
  "Drink coffee"
];

const taskListElement = document.getElementById("taskList");
const taskCountElement = document.getElementById("taskCount");

function showTaskCount(tasks) {
  taskCountElement.textContent = `You have ${tasks.length} tasks today.`;
}

function showTasks(tasks) {
  for (const task of tasks) {
    const listItem = document.createElement("li");
    listItem.textContent = task;
    taskListElement.appendChild(listItem);
  }
}

showTaskCount(tasks);
showTasks(tasks);

Refresh the browser.

You should see a list of tasks on the page.

JavaScript took the array and created HTML elements from it.

This is important.

Very important.

Because many real websites work exactly like this:

This is not just theory.

This is real web development.

Small.

Simple.

But real.

The browser is no longer a decorative potato.

It is working.

How This Code Works

This array stores the tasks:

const tasks = [
  "Learn arrays",
  "Practice loops",
  "Build a small project",
  "Drink coffee"
];

This finds the list in the HTML:

const taskListElement = document.getElementById("taskList");

This finds the paragraph for the task count:

const taskCountElement = document.getElementById("taskCount");

This function shows how many tasks we have:

function showTaskCount(tasks) {
  taskCountElement.textContent = `You have ${tasks.length} tasks today.`;
}

This function creates list items:

function showTasks(tasks) {
  for (const task of tasks) {
    const listItem = document.createElement("li");
    listItem.textContent = task;
    taskListElement.appendChild(listItem);
  }
}

This runs both functions:

showTaskCount(tasks);
showTasks(tasks);

Notice something important.

The array contains the data.

The functions decide what to do with the data.

This keeps the code cleaner.

Not perfect.

But cleaner.

Perfection is suspicious anyway.

Common Mistakes

Forgetting That Arrays Start at Zero

Wrong expectation:

const fruits = ["apple", "banana", "orange"];

console.log(fruits[1]);

You might expect:

apple

But you get:

banana

Because the first item is index 0.

Correct:

console.log(fruits[0]);

Output:

apple

JavaScript starts from zero.

Accept it.

Drink water.

Continue.

Using an Index That Does Not Exist

Example:

const fruits = ["apple", "banana", "orange"];

console.log(fruits[10]);

Output:

undefined

There is no item at index 10.

JavaScript is not angry.

It is just empty there.

Like your fridge after midnight.

Using <= Instead of < in a Loop

Wrong:

const fruits = ["apple", "banana", "orange"];

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

This can print:

apple
banana
orange
undefined

Why?

Because the last valid index is 2.

But fruits.length is 3.

Correct:

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

Use <.

Not <=.

Small symbol.

Big difference.

Like forgetting one screw in a chair.

Forgetting to Clear the List

If you run a function many times, it may add the same items again and again.

Example:

function showTasks(tasks) {
  for (const task of tasks) {
    const listItem = document.createElement("li");
    listItem.textContent = task;
    taskListElement.appendChild(listItem);
  }
}

If this function runs twice, the tasks appear twice.

To avoid this, clear the list first:

function showTasks(tasks) {
  taskListElement.innerHTML = "";

  for (const task of tasks) {
    const listItem = document.createElement("li");
    listItem.textContent = task;
    taskListElement.appendChild(listItem);
  }
}

This removes old content before adding new content.

Very useful.

Especially when your page starts duplicating things like a broken printer.

Practice

Create an array named favoriteLanguages.

It should contain at least three programming languages.

Example:

const favoriteLanguages = ["JavaScript", "Python", "Java"];

Print every language using a for...of loop.

Example:

for (const language of favoriteLanguages) {
  console.log(language);
}

Then create an array named scores.

Example:

const scores = [10, 25, 8, 40, 15];

Print only scores bigger than 20.

Example:

for (const score of scores) {
  if (score > 20) {
    console.log(score);
  }
}

Run the code.

Change values.

Break it.

Fix it.

This is still the best way to learn.

JavaScript likes practice.

And sometimes sacrifice.

Mostly practice.

Mini Challenge

Build a small page with:

Example array:

const products = [
  "Laptop",
  "Mouse",
  "Keyboard",
  "Monitor"
];

Create a function:

function showProducts(products) {
  // create list items here
}

Bonus:

Add another function named showProductCount.

It should show this message:

There are 4 products.

Use:

products.length

This challenge is very close to real web development.

You have data.

You display data.

You keep logic inside functions.

That is how we avoid spaghetti.

Or at least we cook better spaghetti.

Summary

Today you learned:

This is a huge step.

Arrays are everywhere in JavaScript.

When you see a list of products, posts, users, tasks, comments, or photos, there is probably an array somewhere behind it.

Quietly working.

Probably tired.

But useful.

Next Lesson

In the next lesson, we will learn objects.

Objects help you store structured data.

Because sometimes this is not enough:

const user = "Viktor";

Sometimes we need:

const user = {
  name: "Viktor",
  age: 33,
  role: "Developer"
};

Arrays are for lists.

Objects are for details.

Together they are everywhere.

JavaScript is becoming serious now.

Still weird.

But serious.