Codectionary / Developer documentation / JavaScript

Array Basics

Arrays are ordered, zero-indexed collections that can hold values of any type, including a mix of types. They can be created with array literal syntax [] or the Array constructor. The length property reflects the number of elements, and static methods like Array.isArray(), Array.from(), and Array.of() help create or check arrays.

Syntax

const arr = [item1, item2, item3];
arr[index];
arr.length;

Examples

Creating and Accessing Arrays

Basic array creation, indexing, and length.

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

At a glance

Purpose
Application logic and interaction
File extension
.js ยท .mjs
Runs in
Browsers and JavaScript runtimes
Usually used with
HTML, CSS and Web APIs

Specifications & further reading

Related JavaScript documentation