An introduction to JavaScript Arrays

By

Learn JavaScript array basics: create arrays, access values, understand length and empty slots, add or remove items, combine arrays, and find values.

~~~

An array stores an ordered collection of values.

JavaScript arrays are resizable objects. They can contain values of different types:

const values = [1, 'Flavio', true, { color: 'blue' }]

Use Array.isArray() when you need to check a value:

Array.isArray(values) //true
typeof values //'object'

The MDN Array reference and the ECMAScript Array specification document every method and edge case.

Create an array

The simplest way to create an array is an array literal:

const empty = []
const numbers = [1, 2, 3]

Array.of() creates an array from its arguments:

const numbers = Array.of(1, 2, 3)

Be careful with the Array constructor. One numeric argument creates an array with that length, not an array containing the number:

const slots = Array(3)
const number = Array.of(3)

slots.length //3
number //[3]

The three positions in slots are empty slots. They do not contain undefined values.

Use fill() when you want actual values in every position:

const zeros = Array(3).fill(0)

zeros //[0, 0, 0]

Array.from() creates an array from an iterable or array-like value:

const letters = Array.from('hello')

letters //['h', 'e', 'l', 'l', 'o']

Access array items

Array indexes start at zero:

const fruits = ['banana', 'pear', 'apple']

fruits[0] //'banana'