Codectionary / Developer documentation / JavaScript

JavaScript Arrays

JavaScript arrays store an ordered list of values. Create one with [], read items by index starting at 0, and use array methods to add or transform items.

Before you start: Variables: var, let, const

Syntax

const languages = ["HTML", "CSS", "JavaScript"];
console.log(languages[0]); // "HTML"
console.log(languages.length); // 3
languages[1] = "Python"; // replace the second item

Breaking down the syntax

["HTML", "CSS"]
Creates an array with two string values. This is array literal syntax.
languages[0]
Reads the first item.
.push(value)
Changes the original array and returns its new length.
.map(callback)
Creates a new array from the callback results.

How it works

An array literal is a list of comma-separated values inside square brackets, such as ["HTML", "CSS"]. Empty brackets create an empty array. Read an item with its position in brackets: languages[0] is the first item, not the second. Arrays can grow and can contain strings, numbers or objects.

Create the list and read a position

Square brackets create the array. Index 0 selects the first value; reading an absent position returns undefined.

Choose whether to change the original

push() adds to the same array. map() builds another array from callback results. Keep that distinction in mind when several parts of your program use the same list.

Examples

Start empty and add an item

Build a list as lessons are completed, starting with no entries.

const completedLessons = [];
console.log(completedLessons.length); // 0
completedLessons.push("Arrays");
console.log(completedLessons[0]); // "Arrays"
console.log(completedLessons.length); // 1
  1. [] creates an array with no items. push adds an item at the end.
  2. const allows the contents to change; it prevents assigning a different array to completedLessons.

Choose a language

Prints HTML, then 4. Try changing index to 2.

const languages = ["HTML", "CSS", "JavaScript"];
const index = 0;
console.log(languages[index]);
languages.push("Python");
console.log(languages.length);
  1. Prints HTML, then 4. Try changing index to 2.
  2. push changes the same array.

Create lesson labels

Create display labels while keeping the original names.

const languages = ["HTML", "CSS", "JavaScript"];
const labels = languages.map((name, index) => `${index + 1}. Learn ${name}`);
console.log(labels);
console.log(languages);
  1. Create display labels while keeping the original names.
  2. Each returned string becomes an item in the new array.

Create an array literal and access its items

Square brackets hold comma-separated values. Index 0 reads the first item; length - 1 reads the last item of this nonempty array.

const fruits = ["apple", "banana", "cherry"];

console.log(fruits[0]);      // "apple" - first element
console.log(fruits[fruits.length - 1]); // "cherry" - last element
console.log(fruits.length);  // 3

fruits[1] = "blueberry"; // arrays are mutable
console.log(fruits); // ["apple", "blueberry", "cherry"]

Array.isArray() and Array.from()

Checking for arrays and creating them from other iterables.

console.log(Array.isArray([1, 2, 3])); // true
console.log(Array.isArray("hello"));    // false

const fromString = Array.from("abc");
console.log(fromString); // ["a", "b", "c"]

const fromMap = Array.from({ length: 5 }, (_, i) => i * 2);
console.log(fromMap); // [0, 2, 4, 6, 8]

Best practices

  • Use array literal syntax [] rather than new Array() for creating arrays - it is more concise and avoids a quirky single-number-argument edge case
  • Use Array.isArray() rather than typeof to correctly identify arrays, since typeof reports "object" for both
  • Use Array.from() to convert array-like or iterable values (like NodeLists or strings) into real arrays with full method support
  • Remember that arrays are objects, so assigning one array variable to another copies the reference, not the contents

Runtime & versions

Browsers and JavaScript runtimes. Feature availability depends on the language and runtime version used by your project; consult the official reference below.

ECMAScript specification

When should I use this?

Use an array for an ordered collection, such as saved lesson ids or quiz scores. Read by index when position matters; use find() when you need an item with a particular property.

Common mistakes

Reading past the end

The final index in a nonempty dense array is length minus one.

Incorrect

languages[languages.length]

Corrected

languages[languages.length - 1]

Expecting new Array(3) to contain the number 3

A single numeric argument sets the array length and leaves empty slots. Use [3] for one item whose value is 3. Array.of(3) also creates one item.

Incorrect

const scores = new Array(3);
console.log(scores.length); // 3
console.log(scores[0]); // undefined

Corrected

const scores = [3];
console.log(scores.length); // 1
console.log(scores[0]); // 3

Compare approaches

  • map: Transform items.
  • filter: Keep matching items.
  • find: Find the first matching item.

Explore deeper

const is not immutable

const prevents assigning another array to the variable; it does not prevent push or changing items.

Length and copying

Sparse arrays can contain empty slots, so length is not always the number of stored values. Spread and slice make shallow copies; nested objects remain shared.

Specifications & further reading