Arrays

Arrays store ordered lists of values in a single variable.

Syntaxlet fruits = ['apple', 'banana'];

An array is an ordered list of values. Write it with square brackets, separating items with commas.

Key points

  • Items are accessed by index, starting at 0.
  • array.length gives the number of items.
  • An array can hold mixed types.

Example

Try it yourself
Loading editor…
Press Run to execute the code.

When to use it

  • Store a list of product IDs in the current shopping cart to send with a checkout request.
  • Hold a collection of search results returned from an API before rendering them as a list.
  • Keep an ordered queue of pending notifications to display one at a time.

More examples

Declare and access an array

Declares an array literal and accesses elements by zero-based index and the length property.

Example · js
const fruits = ["apple", "banana", "cherry"];
console.log(fruits[0]);      // "apple"
console.log(fruits.length);  // 3

Mixed-type array

Shows that JavaScript arrays can hold values of different types in the same collection.

Example · js
const record = [1, "Alice", true, null];
console.log(record[1]); // "Alice"
console.log(record[3]); // null

Push and pop elements

Uses push to add multiple items to the end of an array and pop to remove and return the last one.

Example · js
const cart = ["book"];
cart.push("pen", "ruler");
console.log(cart);       // ["book", "pen", "ruler"]
const removed = cart.pop();
console.log(removed);    // "ruler"

Discussion

  • Be the first to comment on this lesson.
Arrays — JavaScript | SoundsCode