Skip to main content

JavaScript Arrays 101 – A Beginner’s Guide

Updated 3 min readMarkdown

During our learning phase in JavaScript, one of the first problems you face is managing multiple values efficiently.

Imagine you want to store the names of your favorite fruits.

Without arrays, you would do something like this:

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

This works for a small number of values, but what if you have 100 fruits?

That’s where arrays become useful.


What is an Array?

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

Instead of creating many separate variables, you can store everything together in order.

Think of an array like a list:

["Apple", "Banana", "Mango"]

Arrays help us

  • Store multiple values together

  • Organize data easily

  • Access values quickly using position numbers

  • Loop through items efficiently


How to Create an Array

In JavaScript, arrays are created using square brackets [].

Example

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

Here:

  • fruits is the array name

  • "Apple", "Banana", and "Mango" are the elements inside the array

You can also create arrays of numbers

let marks = [85, 90, 78, 92];

Accessing Elements Using Index

Every element in an array has a position number called an index.

Important:
JavaScript arrays start counting from 0, not 1.

Element Index
Apple 0
Banana 1
Mango 2

Example

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

console.log(fruits[0]);

Output:

Apple

Another example

console.log(fruits[1]);

Output:

Banana

Why Does Index Start From 0?

This is how JavaScript and many programming languages work internally.

So:

  • First item --> index 0

  • Second item --> index 1

  • Third item --> index 2

It may feel strange at first, but you’ll get used to it quickly.


Updating Elements in an Array

You can change any value in an array using its index.

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

fruits[1] = "Orange";

console.log(fruits);

Output

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

Here, "Banana" was replaced with "Orange".


Array Length Property

Arrays have a built-in property called length.

It tells you how many elements are inside the array.

Example

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

console.log(fruits.length);

Output

3

This is very useful when working with loops.


Basic Looping Over Arrays

Looping means going through each element one by one.

The most common beginner-friendly loop is the for loop.

Example

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

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

Output

Apple
Banana
Mango

4 views

No comments yet. Be the first to comment.