Skip to content
Tutorials Center
My learning

Topics

Lesson 49 of 156 ยท Arrays

Arrays

Learn JavaScript arrays from scratch. Create them, read and change items by index, use length and at(), loop over them and check for arrays with Array.isArray.

An array is an ordered list of values. A shopping list, the scores in a game, the rows of a table, the messages in a chat: whenever you have "several of something" in a particular order, you reach for an array.

Each value in an array is called an item (or element), and each item has a numbered position called its index. Indexes start at 0. Arrays can hold any mix of values, grow and shrink as you go, and come with dozens of built-in methods. This lesson covers the basics: creating arrays, reading and changing items, length, the handy at() method and how arrays relate to objects. The next lessons build on this with methods for adding and removing, transforming, searching and sorting.

Creating arrays

The usual way to create an array is an array literal: square brackets with items separated by commas.

JS Array literals

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The console shows each array with its length and items. In real code, arrays usually hold values of one kind, like all strings or all user objects. Mixed arrays are legal but harder to work with.

Declare arrays with const unless you plan to point the variable at a different array. const doesn't stop you from changing the items; it only stops reassignment (see Variables).

Other ways to create arrays

You'll occasionally need these:

JavaScript
Array.of(7);              // [7]
Array.from("hey");        // ["h", "e", "y"]
Array.from({ length: 3 }, (_, i) => i * 10); // [0, 10, 20]
new Array(3).fill(0);     // [0, 0, 0]

Array.from() turns any iterable or array-like value into a real array, and its optional second argument transforms each item on the way. You'll see more of it in Array Recipes.

Avoid new Array(n) for a list of values. new Array(3) makes an empty array with length 3 and three holes, while new Array(3, 4) makes [3, 4]. The behavior changes with the number of arguments, which causes bugs. Use literals, or Array.of() if you really need a function.

Reading items by index

Put an index in square brackets to read an item. The first item is at index 0, the second at 1 and so on, so the last item is at length - 1:

JS Indexes start at zero

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Reading an index that doesn't exist gives undefined rather than an error. That's convenient, but it also means typos can go unnoticed. Note that colors[-1] does not give you the last item in JavaScript, unlike in Python.

at(): counting from the end

The at() method reads an item by index too, but it also accepts negative indexes, which count backwards from the end. at(-1) is the last item, at(-2) the one before it:

JavaScript
const queue = ["Ana", "Ben", "Cai", "Dev"];

queue.at(0);   // "Ana"
queue.at(-1);  // "Dev"
queue.at(-2);  // "Cai"
queue.at(9);   // undefined

queue.at(-1) is much easier to read than queue[queue.length - 1], especially when the array has a long name or comes from a function call. at() is supported in all modern browsers (since 2022), and strings have it too.

Changing items

Assign to an index to replace an item. Assigning beyond the end adds an item there:

JS Writing by index

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Arrays with gaps are called sparse arrays. Some methods skip the holes and others treat them as undefined, which gets confusing, so avoid creating them. To add items, use push() and friends from the next lesson.

The length property

length is always one more than the highest index. It updates automatically as the array grows, and you can also set it:

JavaScript
const tasks = ["wash", "dry", "fold", "store"];

tasks.length = 2;     // truncates the array
console.log(tasks);   // ["wash", "dry"]

tasks.length = 0;     // empties it completely
console.log(tasks);   // []

Setting length to a smaller number permanently removes items. It's a quick way to empty an array in place, which matters when other code holds a reference to the same array (see Copying Objects). Assigning tasks = [] instead would only work with let, and would leave other references pointing at the old, full array.

Looping over an array

The two everyday loops for arrays are the classic for loop and for...of:

JS Looping

Press Run (or Ctrl + Enter) to see the console output here.

No output.

for...of is the cleanest choice when you just need each value. Use entries() with destructuring when you need the index too. Avoid for...in for arrays: it iterates keys as strings and can include extra properties.

Array methods such as forEach, map and filter are often even better than loops. They get their own lesson: map, filter, reduce and forEach.

Arrays are objects

typeof reports arrays as "object", because that's what they are: special objects whose keys are indexes, with an automatic length and array methods inherited from Array.prototype.

JS Detecting arrays

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Because typeof can't tell an array from an object, use Array.isArray() to check. It's reliable, unlike instanceof Array, which can fail for arrays that come from another window or iframe.

Being objects has two other consequences:

  • Arrays are passed and assigned by reference. const b = a doesn't copy the array. Use [...a] for that, as you saw in Copying Objects.
  • === compares identity. Two arrays with the same items are not equal unless they're the same array.

You'll also meet array-like objects, which have numbered keys and a length but none of the methods. A string, a function's arguments object and a DOM NodeList are common examples. Convert them with Array.from() or spread when you need real array methods.

Arrays inside arrays

An array can hold other arrays, which gives you grids and tables:

JavaScript
const board = [
  ["X", "O", "X"],
  [" ", "X", "O"],
  ["O", " ", "X"],
];

console.log(board[1][2]); // "O": row 1, column 2
board[1][0] = "O";        // change a cell

The first index picks the row, the second picks the item in that row. console.table(board) displays a grid like this nicely in the console.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What is letters[3] when const letters = ["a", "b", "c"];?

    The indexes are 0, 1 and 2. Reading a missing index gives undefined, not an error.
  2. 2. Which expression returns the last item of items?

    at() accepts negative indexes. items[-1] looks for a property named "-1", and items[items.length] is one past the end.
  3. 3. What does typeof [1, 2, 3] return?

    Arrays are objects, so typeof says "object". Use Array.isArray() to detect them.
  4. 4. After const nums = [1, 2, 3, 4]; nums.length = 2;, what is nums?

    Setting length to a smaller value truncates the array from the end.
  5. 5. Why should you avoid new Array(5) for a list of values?

    A single number argument sets the length and leaves holes; two or more arguments become items. Use literals or Array.of() instead.

Summary

  • Arrays are ordered lists; create them with literals like ["a", "b"].
  • Indexes start at 0; the last item is at length - 1, and missing indexes give undefined.
  • at() reads by index and accepts negative numbers: arr.at(-1) is the last item.
  • Assign to an index to change an item; avoid writing past the end, which creates holes.
  • length updates automatically and can be set to truncate or empty an array.
  • Loop with for...of, or with entries() when you need the index.
  • Arrays are objects: use Array.isArray() to detect them, and remember they're shared by reference.

Next: Adding, Removing and Slicing โ€” push, pop, splice, slice and their non-mutating cousins.