References

Beginner-friendly references for web development, with live, editable examples.

The JavaScript Array object

Object JavaScript All modern browsers Updated
Quick answer

The Array object holds an ordered list of values and comes with dozens of built-in methods. Create one with a literal [1, 2, 3]. Transform it with map(), filter() and reduce(); check one with Array.isArray(). Arrays are zero-indexed and can hold mixed types.

Overview

The Array is JavaScript's workhorse for ordered collections — a list of values you can index, loop over and transform. You almost always create one with a literal, const list = [1, 2, 3], rather than the new Array() constructor. Arrays are zero-indexed (list[0] is the first item), can hold any mix of types, and grow or shrink freely.

What makes arrays so central is their toolbox of methods. The transformers — map(), filter(), reduce() — turn one array into another without mutating the original, and chain together into readable data pipelines. The searchers — find(), includes(), indexOf() — locate values. The mutators — push(), splice(), sort() — change the array in place.

A few static helpers live on Array itself rather than on instances. Array.isArray(x) is the reliable way to check whether something is an array (since typeof an array is "object"). Array.from(x) builds an array from an iterable or array-like value — handy for converting a NodeList. And the length property tells you how many items it holds.

Syntax

const list = [1, 2, 3];          // array literal
const empty = [];

list.length;                     // 3
list[0];                         // 1
Array.isArray(list);             // true
Array.from("abc");               // ["a", "b", "c"]

Example

Live example
<pre id="out" style="font:15px ui-monospace,monospace"></pre>
<script>
  const nums = [5, 12, 8, 21, 3];

  const big = nums.filter(n => n > 5).map(n => n * 10);

  document.getElementById('out').textContent =
    'length: ' + nums.length + '\n' +
    'result: ' + big.join(', ') + '\n' +
    'isArray: ' + Array.isArray(nums);
</script>

Best practices

  • Create arrays with literals [] rather than the new Array() constructor.
  • Reach for map()/filter()/reduce() for non-mutating transforms you can chain.
  • Check for an array with Array.isArray(x), not typeof.
  • Convert array-like values (like a NodeList) with Array.from(x) or the spread operator.

Frequently asked questions

How do I create an array in JavaScript?
Use a literal: const arr = [1, 2, 3]. This is preferred over new Array().
How do I check if a variable is an array?
Use Array.isArray(value). typeof an array returns "object", so it can't tell arrays apart on its own.
How do I get the number of items in an array?
Read its length property: arr.length.
What are the most useful array methods?
map(), filter(), reduce(), find(), forEach(), includes() and push() cover most everyday work.