JavaScript Arrays: Basics, Methods, and Practical Examples

JavaScript arrays are one of the most important ways to store ordered data. They let you keep multiple values in a single variable, then read, update, search, and transform those values with built-in methods.

Quick answer: A JavaScript array is an ordered list of values. Use it when you need indexed access, easy iteration, or collection methods like push(), map(), and filter().

Difficulty: Beginner

You'll understand this better if you know: variables, basic JavaScript syntax, and how objects and values are assigned in code.

1. What Is JavaScript Arrays?

An array is a single value that can hold multiple items in a specific order. Each item has an index, which is its position in the array, starting at 0.

In JavaScript, arrays are a special kind of object with array-specific behavior and a built-in length property.

2. Why JavaScript Arrays Matter

Arrays solve the problem of storing many related values without creating many separate variables. Instead of managing firstName, secondName, and thirdName, you can keep them in one collection and process them consistently.

They matter because so much everyday programming uses lists:

Arrays are also the foundation for many common JavaScript patterns, including iteration with for loops and higher-order functions like map() and reduce().

3. Basic Syntax or Core Idea

The simplest way to create an array is with square brackets. Each value is separated by a comma.

Create an array

This example shows a list of strings and how to read the first and second items.

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

console.log(fruits[0]); // apple
console.log(fruits[1]); // banana
console.log(fruits.length); // 3

fruits[0] returns the first item, and length tells you how many items are in the array. Remember that the last index is always one less than the length.

Update an item

You can replace a value by assigning to a specific index.

const scores = [10, 20, 30];

scores[1] = 25;
console.log(scores); // [10, 25, 30]

Even when the variable itself is declared with const, the array contents can still change because the array reference is constant, not the values inside it.

4. Step-by-Step Examples

This section shows common array operations you will use every day.

Example 1: Add items to the end

Use push() to append one or more values to the end of an array.

const tasks = ["write docs"];

tasks.push("review code");
tasks.push("publish");

console.log(tasks); // ["write docs", "review code", "publish"]

This is the standard way to grow a list from the end.

Example 2: Remove items from the end

Use pop() to remove and return the last item.

const colors = ["red", "green", "blue"];

const lastColor = colors.pop();

console.log(lastColor); // blue
console.log(colors); // ["red", "green"]

Use this when the most recent item should be removed.

Example 3: Add items to the beginning

Use unshift() to insert values at the front of the array.

const queue = ["B", "C"];

queue.unshift("A");

console.log(queue); // ["A", "B", "C"]

This is useful when order matters and new items must appear first.

Example 4: Loop through an array

A for...of loop is a simple way to read every item in order.

const names = ["Ada", "Linus", "Grace"];

for (const name of names) {
  console.log(name);
}

This prints each item one by one and is often easier to read than manually managing indexes.

Example 5: Transform with map()

Use map() when you want a new array with the same number of items but modified values.

const prices = [10, 20, 30];

const withTax = prices.map((price) => price * 1.2);

console.log(withTax); // [12, 24, 36]

map() does not change the original array; it creates a new one.

5. Practical Use Cases

Arrays are a good fit for many real tasks in JavaScript applications.

Choose arrays when the order of items matters or when you need to process the whole collection with loops or array methods.

6. Common Mistakes

Mistake 1: Using the wrong index

Array indexes start at 0, not 1. New developers often expect the first item to be at position one, which leads to skipped values or undefined.

Problem: The code asks for an index that does not exist, so JavaScript returns undefined instead of the value you expected.

const letters = ["A", "B", "C"];

console.log(letters[1]); // B, not A
console.log(letters[3]); // undefined

Fix: Use 0 for the first item and check that the index is within bounds.

const letters = ["A", "B", "C"];

console.log(letters[0]); // A
console.log(letters[letters.length - 1]); // C

The corrected version uses valid indexes and matches how arrays are actually numbered.

Mistake 2: Confusing arrays with objects

Arrays are objects, but they are not meant to be accessed with arbitrary names in the same way as plain objects. Using string keys on an array can create properties that do not behave like normal items.

Problem: This code adds a custom property instead of a real array element, so methods like length and loops do not treat it like list data.

const items = [];

items.name = "example";

console.log(items.length); // 0
console.log(items.name); // example

Fix: Use numeric indexes for array items, or use a plain object if you need named properties.

const items = ["example"];

console.log(items.length); // 1
console.log(items[0]); // example

The fixed version stores data in a way that array methods understand.

Mistake 3: Expecting map() to change the original array

map() returns a new array. If you ignore the return value, it can look like nothing happened.

Problem: The original array is left unchanged, so later code still sees the old values.

const numbers = [1, 2, 3];

numbers.map((n) => n * 2);

console.log(numbers); // [1, 2, 3]

Fix: Save the result in a new variable or assign it back when that is what you want.

const numbers = [1, 2, 3];

const doubled = numbers.map((n) => n * 2);

console.log(doubled); // [2, 4, 6]

The corrected version works because it uses the new array returned by map().

7. Best Practices

Practice 1: Use the right method for the job

Choose methods that match your intent. That makes code easier to read and avoids unnecessary work.

const names = ["Mia", "Noah", "Zoe"];

const filtered = names.filter((name) => name.startsWith("N"));

filter() expresses selection clearly and avoids manual loops when you only need matching items.

Practice 2: Prefer non-mutating methods when you need a new list

Methods like map(), filter(), and slice() create new arrays. This helps prevent accidental side effects.

const original = [1, 2, 3];
const copy = original.slice();

console.log(copy); // [1, 2, 3]

This is safer when other parts of your code still depend on the original data.

Practice 3: Check for empty arrays before using indexes

If you read the first or last item, confirm that the array actually has items first. This prevents confusing undefined values.

const messages = [];

if (messages.length > 0) {
  console.log(messages[0]);
} else {
  console.log("No messages yet.");
}

That check makes your code safer and easier to debug.

8. Limitations and Edge Cases

Note: If you see surprising behavior with indexes or missing items, check whether you created a hole in the array or used the wrong method for removal.

9. Practical Mini Project

Here is a small working example that manages a simple list of todo items in plain JavaScript. It shows how arrays support adding, removing, and displaying items together.

const todos = ["Learn arrays", "Write examples"];

function addTodo(todo) {
  todos.push(todo);
}

function removeTodo(index) {
  if (index >= 0 && index < todos.length) {
    todos.splice(index, 1);
  }
}

function renderTodos() {
  return todos
    .map((todo, index) => `${index}: ${todo}`)
    .join("\n");
}

addTodo("Review pull request");
removeTodo(0);

console.log(renderTodos());

This example uses an array as the source of truth. New items are appended with push(), removal is handled with splice(), and rendering uses map() to turn the list into text.

10. Key Points

11. Practice Exercise

Create a small function that accepts an array of numbers and returns a new array containing only the even numbers, each doubled.

Solution:

function evenAndDouble(numbers) {
  return numbers
    .filter((number) => number % 2 === 0)
    .map((number) => number * 2);
}

const input = [1, 2, 3, 4, 5, 6];
console.log(evenAndDouble(input)); // [4, 8, 12]

12. Final Summary

JavaScript arrays are the standard way to store ordered lists of values. They give you indexed access, a length property, and a wide range of methods for adding, removing, searching, and transforming data.

Once you understand indexes, mutation, and the difference between methods that change the original array and methods that return a new one, arrays become easy to use in real programs. That knowledge carries into almost every part of JavaScript development, from basic scripts to larger web applications.

Next, practice reading and modifying arrays with push(), pop(), map(), and filter(), then try building a small list-based feature such as a shopping cart or task tracker.