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.

  • Arrays can store any mix of values, including numbers, strings, objects, and even other arrays.
  • Items are accessed by index, such as items[0].
  • Arrays are mutable, so you can change their contents after creation.
  • They are ideal for lists of data that you want to loop over or process.

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:

  • Showing product cards on a page
  • Storing messages in a chat app
  • Tracking scores, tags, or task items
  • Filtering search results
  • Building menus, tables, and timelines

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

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.

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

console.log(fruits[0]); // apple
console.log(fruits[1]); // banana
console.log(fruits.length); // 3
Output✓ Tested · Node 24
apple
banana
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.

JavaScript
const scores = [10, 20, 30];

scores[1] = 25;
console.log(scores); // [10, 25, 30]
Output✓ Tested · Node 24
[ 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.

JavaScript
const tasks = ["write docs"];

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

console.log(tasks); // ["write docs", "review code", "publish"]
Output✓ Tested · Node 24
[ "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.

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

const lastColor = colors.pop();

console.log(lastColor); // blue
console.log(colors); // ["red", "green"]
Output✓ Tested · Node 24
blue
[ "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.

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

queue.unshift("A");

console.log(queue); // ["A", "B", "C"]
Output✓ Tested · Node 24
[ "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.

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

for (const name of names) {
  console.log(name);
}
Output✓ Tested · Node 24
Ada
Linus
Grace

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.

JavaScript
const prices = [10, 20, 30];

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

console.log(withTax); // [12, 24, 36]
Output✓ Tested · Node 24
[ 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.

  • A shopping cart that stores selected products in order
  • A to-do list where each task is a separate item
  • A list of usernames or tags from an API response
  • Search filtering, where you keep only matching entries
  • Table rows, menu options, or gallery images
  • Collected form values, such as checked checkboxes

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.

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

console.log(letters[1]); // B, not A
console.log(letters[3]); // undefined
Output✓ Tested · Node 24
B
undefined

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

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

console.log(letters[0]); // A
console.log(letters[letters.length - 1]); // C
Output✓ Tested · Node 24
A
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.

JavaScript
const items = [];

items.name = "example";

console.log(items.length); // 0
console.log(items.name); // example
Output✓ Tested · Node 24
0
example

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

JavaScript
const items = ["example"];

console.log(items.length); // 1
console.log(items[0]); // example
Output✓ Tested · Node 24
1
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.

JavaScript
const numbers = [1, 2, 3];

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

console.log(numbers); // [1, 2, 3]
Output✓ Tested · Node 24
[ 1, 2, 3 ]

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

JavaScript
const numbers = [1, 2, 3];

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

console.log(doubled); // [2, 4, 6]
Output✓ Tested · Node 24
[ 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.

JavaScript
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.

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

console.log(copy); // [1, 2, 3]
Output✓ Tested · Node 24
[ 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.

JavaScript
const messages = [];

if (messages.length > 0) {
  console.log(messages[0]);
} else {
  console.log("No messages yet.");
}
Output✓ Tested · Node 24
No messages yet.

That check makes your code safer and easier to debug.

8. Limitations and Edge Cases

  • Array indexes are non-negative integers. Negative values like arr[-1] do not give the last element; they create or read a property named -1.
  • Arrays can be sparse. If you assign to a far index, you may create empty slots instead of filled values.
  • length changes automatically when you add or remove items at the end, but not when you add custom properties.
  • delete removes an element without shifting later items, which often leaves a hole. Use splice() when you want items to shift.
  • Large arrays can be memory-heavy, so repeated copying in tight loops may become expensive.
  • Methods that mutate arrays can make debugging harder if multiple parts of your program share the same array reference.

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.

JavaScript
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());
Output✓ Tested · Node 24
0: Write examples
1: Review pull request

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

  • Arrays store ordered collections of values.
  • Indexes start at 0, and length tells you how many items are present.
  • Use push(), pop(), unshift(), and shift() for common insert and remove operations.
  • Use map(), filter(), and reduce() to transform array data.
  • Arrays are mutable, but many methods return new arrays instead of changing the original.
  • Choose arrays when order and iteration matter.

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.

  • Input example: [1, 2, 3, 4, 5, 6]
  • Expected output: [4, 8, 12]
  • Hint: combine filter() and map().
Show solution
JavaScript
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]
Output✓ Tested · Node 24
[ 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.