JavaScript

Arrays

An array is an ordered list of values, written with square brackets: const fruits = ["apple", "banana", "cherry"];. Arrays can hold any type of value, including a mix of types, though in practice they usually hold similar things. Access an item by its index, starting from 0: fruits[0] is "apple", fruits[2] is "cherry". fruits.length gives you the number of items (3 here). Arrays have useful built-in methods for adding and removing items. .push("date") adds to the end. .pop() removes the last item and returns it. .unshift("apricot") adds to the beginning. .shift() removes the first item and returns it. fruits.indexOf("banana") returns the index of the first match (1), or -1 if it's not found at all. fruits.includes("banana") returns a simple true/false instead. You'll cover more powerful array methods map, filter, forEach, reduce in the next dedicated topic.

Why this matters

  • ·Arrays let you store and manage a whole list of related values under one name.
  • ·Built-in methods like push, pop, and includes handle common list operations without custom code.
  • ·Index-based access makes it easy to work with a specific item's position.

Common mistakes

  • ·Array indexes start at 0, not 1 accessing fruits[3] on a 3-item array returns undefined, not the last item.
  • ·Confusing .pop() (removes from the end) with .shift() (removes from the beginning) leads to unexpected results.
  • ·Modifying an array while looping over it can cause confusing, hard-to-predict bugs.
Your codeHTML
Live preview

Frequently asked questions

0 the first item is at index 0, not 1.

Practice questions

Question 1

Create an array of three of your favorite subjects, then display the second one.

Your codeHTML
Live preview

Question 2

Add a fourth item to an existing array using .push(), then display the full array.

Your codeHTML
Live preview

Quick check

Just for this topic answer honestly, then check yourself.

1 / 3

What index is the first item of an array?