Arrays for Lists of Data

Course: JavaScript Beginner

Lesson 11: Arrays for Lists of Data

Level

Beginner

Estimated Reading Time

10–15 minutes

Goal

By the end of this lesson, the learner will be able to:

  • Create arrays and access elements by index
  • Add and remove items using push, pop, shift, and unshift
  • Use length, includes, and indexOf to inspect an array

Frontend Development Context

Arrays are the standard way to work with lists of data in JavaScript. Search results, shopping cart items, a user's saved posts, the steps in a multi-page form, a list of notifications — all of these are naturally represented as arrays. Knowing how to create, read, and modify arrays is essential for building any UI that displays or manages a collection of things.

The methods you use on arrays determine how efficiently and clearly your code handles list data. Knowing when to push vs unshift, how to check membership with includes, and how to find a position with indexOf gives you the tools to build features like tag management, item selection, cart updates, and search filtering.

Explanation

An array is an ordered list of values. You create one with square brackets: const colors = ["red", "green", "blue"]. Items in an array are indexed starting at 0, so colors[0] is "red" and colors[2] is "blue". You can access an item by its index, and you can change an item by assigning to its index.

The .length property returns the number of items in the array. The last item is always at index array.length - 1.

Adding items: .push(item) adds an item to the end of the array. .unshift(item) adds an item to the beginning. Both return the new length of the array.

Removing items: .pop() removes and returns the last item. .shift() removes and returns the first item. These mutate the original array.

.includes(value) returns true if the array contains the value and false if it does not. This is useful for checking whether a user has already added a tag, selected an option, or visited a page.

.indexOf(value) returns the index of the first matching item, or -1 if it is not found. This is useful when you need the position of an item — for example, to remove it from the array.

Arrays can hold any type of value, and values do not have to be the same type. In practice, arrays most often hold values of the same type — a list of strings, a list of numbers, or a list of objects.

Code Example

This example manages a list of selected tags that a user can add to or remove from:

const selectedTags = [];
const availableTags = ["JavaScript", "CSS", "HTML", "React", "Node.js"];

function addTag(tag) {
  if (!selectedTags.includes(tag)) {
    selectedTags.push(tag);
    console.log(`Added: ${tag}`);
  } else {
    console.log(`${tag} is already selected`);
  }
}

function removeTag(tag) {
  const index = selectedTags.indexOf(tag);
  if (index !== -1) {
    selectedTags.splice(index, 1);
    console.log(`Removed: ${tag}`);
  }
}

addTag("JavaScript");  // Added: JavaScript
addTag("CSS");         // Added: CSS
addTag("JavaScript");  // JavaScript is already selected
removeTag("CSS");      // Removed: CSS
console.log(selectedTags.length); // 1

Code Explanation

selectedTags starts as an empty array. The addTag function first checks with .includes() whether the tag is already in the list — preventing duplicates. If not, .push() adds it to the end.

removeTag uses .indexOf() to find the position of the tag. If the result is not -1 (meaning the tag was found), .splice(index, 1) removes exactly one element at that index. splice is a powerful method that removes items from a specific position — the first argument is the starting index and the second is how many items to remove.

The !selectedTags.includes(tag) pattern — using ! to check for absence — is very common in array management. It guards against duplicates without needing a loop.

After removing "CSS", selectedTags contains only ["JavaScript"], so .length returns 1. This kind of tag selection logic appears in search filters, form inputs with multi-select chips, and content categorization interfaces.

Pattern Highlights

Positive Pattern: Use .includes() before .push() when building a unique list — it is readable and prevents duplicate entries without needing a manual loop.

⚠️ Neutral Note: .push(), .pop(), .shift(), .unshift(), and .splice() all mutate the original array. If you need to keep the original, make a copy first using the spread operator: const copy = [...original].

Negative Pattern: Using array[array.length] to add an item instead of .push() works but is confusing and error-prone. Use the dedicated method.

Common Mistakes

Mistake 1: Accessing an index that does not exist

Accessing an index beyond the array's length returns undefined, not an error. This can silently break downstream code.

const fruits = ["apple", "banana", "cherry"];
console.log(fruits[5]); // undefined — no error, but also no value

const name = fruits[5].toUpperCase(); // TypeError: Cannot read properties of undefined

Always check the index is valid before accessing it, or use .at() and guard with optional chaining when appropriate.

Mistake 2: Checking length to see if an item exists

Some beginners check if (array.length) to see if an item is present, when they actually want to check whether a specific value is in the array.

const selected = ["HTML", "CSS"];
const tag = "JavaScript";

if (selected.length) {
  console.log("JavaScript is selected"); // always runs when array is non-empty!
}

// Correct:
if (selected.includes(tag)) {
  console.log("JavaScript is selected");
}

.length tells you how many items are in the array. .includes() tells you whether a specific value is present.

Mistake 3: Confusing indexOf return value

indexOf returns -1 when the item is not found, not false or null. Checking if (index) instead of if (index !== -1) fails when the item is at index 0, because 0 is falsy.

const items = ["a", "b", "c"];
const index = items.indexOf("a"); // 0 — item IS in the array at position 0

if (index) { // 0 is falsy — this block does NOT run!
  console.log("Found");
}

// Correct:
if (index !== -1) {
  console.log("Found"); // runs correctly
}

Always compare indexOf results to -1 explicitly.

Quick Recap

  • Arrays are ordered lists of values; items are accessed by index starting at 0
  • .push() adds to the end; .unshift() adds to the beginning; .pop() removes from the end; .shift() removes from the beginning
  • .includes() checks for membership; .indexOf() returns the position (or -1 if not found)
  • Array mutation methods change the original array — make a copy with spread ([...arr]) if you need to preserve the original

Ready to test your understanding? Take the quiz to reinforce what you learned.

© 2026 Ant Skillsv.26.07.07-23:01