Skip to main content

Command Palette

Search for a command to run...

Understanding Arrays in JavaScript: A Beginner's Guide

Updated
5 min read
Understanding Arrays in JavaScript: A Beginner's Guide
A

Hi, I’m Abdul Samad. A web development learner and tech enthusiast. I write about what I learn, share practical coding tips, and publish in-depth blogs on programming and modern web development.

Check out my full collection of blogs on Hashnode: https://abdulsamad30.hashnode.dev/

Connect with me on X for quick updates and insights: @abdul_sama60108

If you've ever made a shopping list, you already understand the basic idea behind arrays. Just like you wouldn't write each grocery item on a separate piece of paper, programmers use arrays to store related data together in one organized place.

What Are Arrays and Why Do We Need Them?

Imagine you're building a program to track student marks in a class. Without arrays, you'd have to create separate variables for each student:

let student1Mark = 85;
let student2Mark = 92;
let student3Mark = 78;
let student4Mark = 88;
let student5Mark = 95;

This quickly becomes messy and impractical. What if you have 50 students? Or 500?

You'd need to create hundreds of variables and manage each one individually.

Arrays solve this problem by letting you store multiple values in a single variable. Think of an array as a container that holds a collection of items in a specific order. Each item has a numbered position, making it easy to find and work with your data.

An array is a collection of values stored in order, where each value can be accessed using its position number.

How to Create an Array

Creating an array in JavaScript is straightforward. You use square brackets [] and separate each value with a comma:

let fruits = ["apple", "banana", "orange", "mango"];

You can store different types of data in arrays:

let marks = [85, 92, 78, 88, 95];
let tasks = ["Buy groceries", "Finish homework", "Call mom"];
let mixedArray = [25, "John", true, 3.14];

You can also create an empty array and add values later:

let emptyArray = [];

Accessing Elements Using Index

Each item in an array has a position number called an index. Here's the important part: indexing starts from 0, not 1. This means the first element is at index 0, the second at index 1, and so on.

To access an element, you write the array name followed by the index in square brackets:

let fruits = ["apple", "banana", "orange", "mango"];

console.log(fruits[0]);  // Output: apple
console.log(fruits[1]);  // Output: banana
console.log(fruits[2]);  // Output: orange
console.log(fruits[3]);  // Output: mango

If you try to access an index that doesn't exist, JavaScript returns undefined:

console.log(fruits[10]);  // Output: undefined

Think of array indices like apartment numbers in a building, except the first apartment is numbered 0 instead of 1.

Updating Elements

Once you've created an array, you're not stuck with those values forever. You can change any element by accessing its index and assigning a new value:

let fruits = ["apple", "banana", "orange", "mango"];

fruits[1] = "grapes";
console.log(fruits);  // Output: ["apple", "grapes", "orange", "mango"]

You can update multiple elements:

fruits[0] = "pineapple";
fruits[3] = "watermelon";
console.log(fruits);  // Output: ["pineapple", "grapes", "orange", "watermelon"]

This flexibility makes arrays perfect for storing data that might change over time, like a to-do list where you mark items as complete or a scoreboard that updates during a game.

Array Length Property

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

let fruits = ["apple", "banana", "orange", "mango"];
console.log(fruits.length);  // Output: 4

let marks = [85, 92, 78];
console.log(marks.length);  // Output: 3

The length property is incredibly useful. You can use it to access the last element of an array without knowing exactly how many elements there are:

let fruits = ["apple", "banana", "orange", "mango"];
let lastFruit = fruits[fruits.length - 1];
console.log(lastFruit);  // Output: mango

We subtract 1 because indices start at 0, so the last element is always at position length - 1.

Basic Looping Over Arrays

One of the most common tasks when working with arrays is going through each element one by one. This is called looping or iterating. The most straightforward way to do this is with a for loop:

let fruits = ["apple", "banana", "orange", "mango"];

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

Output:

apple
banana
orange
mango

Let's break down what's happening:

  • let i = 0 — We start at index 0 (the first element)

  • i < fruits.length — We continue as long as i is less than the array length

  • i++ — After each loop, we increase i by 1

  • fruits[i] — We access the element at the current index

Here's a practical example that calculates the total of all marks:

let marks = [85, 92, 78, 88, 95];
let total = 0;

for (let i = 0; i < marks.length; i++) {
    total += marks[i];
}

console.log("Total marks: " + total);  // Output: Total marks: 438

Looping makes arrays powerful because you can perform the same operation on every element without writing repetitive code.

Practice Assignment

Now it's your turn to practice what you've learned. Try this exercise:

Task 1: Create an array containing 5 of your favorite movies.

Task 2: Print the first and last movie from your array.

Task 3: Change one of the movies to a different title and print the updated array.

Task 4: Loop through the entire array and print each movie with its position number (starting from 1 for readability).

Try solving this on your own before looking at the solution. The best way to learn programming is by writing code yourself!


Arrays are fundamental to programming, and you'll use them constantly as you build more complex applications.

They help you organize data efficiently and work with collections of information in a structured way.

Master these basics, and you'll have a solid foundation for everything that comes next.

FIN ✌️