Skip to content

JavaScript Arrays

JavaScript Arrays: Storing and Managing Collections

Section titled “JavaScript Arrays: Storing and Managing Collections”

JavaScript arrays are versatile, ordered collections used to store multiple values (of any type) in a single variable. They are a fundamental data structure for managing lists of items.

The most common and preferred way to create an array is using an array literal []:

const fruits = ["Apple", "Banana", "Cherry"];
const numbers = [1, 2, 3, 4, 5];
const mixedArray = ["Hello", 100, true, { name: "John" }, ["nested", "array"]];
const emptyArray = [];

Spaces and line breaks are not important within array literals for readability:

const cars = [
"Saab",
"Volvo",
"BMW"
];

Trailing commas (e.g., [1, 2, 3,]) are allowed and generally safe in modern JavaScript environments, but were problematic in older IE versions.

Using new Array() (Less Common, Potential Pitfalls)

Section titled “Using new Array() (Less Common, Potential Pitfalls)”

You can also create arrays using the Array constructor:

const arr1 = new Array("Saab", "Volvo", "BMW"); // Creates an array with these elements
const arr2 = new Array(10, 20, 30);
// Pitfall: If new Array() is called with a single numeric argument,
// it creates an array with that length (empty slots), not an array with that number as an element.
const arrLength5 = new Array(5); // Creates an empty array with length 5: [empty x 5]
console.log(arrLength5.length); // 5
console.log(arrLength5[0]); // undefined
// To create an array with a single number element:
const singleNumArr = [42]; // Preferred
// const singleNumArrAlt = new Array(42); // This creates an array of length 42!
// For simplicity, readability, and avoiding pitfalls, array literals `[]` are almost always preferred.

Array elements are accessed using zero-based indexing (the first element is at index 0).

const colors = ["Red", "Green", "Blue"];
console.log(colors[0]); // Output: "Red"
console.log(colors[1]); // Output: "Green"
console.log(colors[2]); // Output: "Blue"
console.log(colors[3]); // Output: undefined (index out of bounds)

You can change the value of an element by assigning to its index:

colors[1] = "Yellow";
console.log(colors); // Output: ["Red", "Yellow", "Blue"]

Arrays come with many built-in properties and methods that make them powerful.

The length property returns the number of elements in an array. It is always one more than the highest array index.

const numbers = [10, 20, 30, 40];
console.log(numbers.length); // Output: 4
// The length property is writable.
// Setting it to a smaller value truncates the array.
// Setting it to a larger value creates sparse arrays (empty slots).
numbers.length = 2;
console.log(numbers); // Output: [10, 20]
console.log(numbers.length); // Output: 2

Adding and Removing Elements (Mutating Methods)

Section titled “Adding and Removing Elements (Mutating Methods)”
  • push(item1, ..., itemN): Adds one or more elements to the end of an array and returns the new length.
  • pop(): Removes the last element from an array and returns that element.
  • unshift(item1, ..., itemN): Adds one or more elements to the beginning of an array and returns the new length.
  • shift(): Removes the first element from an array and returns that element.
const tasks = ["Write code"];
tasks.push("Test code", "Deploy code"); // tasks is now ["Write code", "Test code", "Deploy code"]
const removedTask = tasks.pop(); // removedTask is "Deploy code", tasks is ["Write code", "Test code"]
tasks.unshift("Plan features"); // tasks is now ["Plan features", "Write code", "Test code"]
const firstTask = tasks.shift(); // firstTask is "Plan features", tasks is ["Write code", "Test code"]

splice(startIndex, deleteCount, item1, ..., itemN): A versatile method to add, remove, or replace elements. Modifies the original array and returns an array of deleted elements.

const months = ["Jan", "March", "April", "June"];
// Insert 'Feb' at index 1
months.splice(1, 0, "Feb");
// months is now ["Jan", "Feb", "March", "April", "June"]
// Replace 1 element at index 3 ('April') with 'May'
months.splice(3, 1, "May");
// months is now ["Jan", "Feb", "March", "May", "June"]
// Remove 1 element at index 0
const deleted = months.splice(0, 1);
// deleted is ["Jan"], months is ["Feb", "March", "May", "June"]
for (let i = 0; i < fruits.length; i++) {
console.log(fruits[i]);
}

Executes a provided function once for each array element.

fruits.forEach(function(fruit, index, array) {
console.log(`Index ${index}: ${fruit}`);
});
// Using arrow function:
fruits.forEach((fruit, index) => console.log(`${index}: ${fruit}`));

for...of loop (ES6) - Preferred for iterating values

Section titled “for...of loop (ES6) - Preferred for iterating values”

Iterates over the values of iterable objects, including arrays.

for (const fruit of fruits) {
console.log(fruit);
}

Modern Array Methods (Non-Mutating - Return New Arrays)

Section titled “Modern Array Methods (Non-Mutating - Return New Arrays)”

These methods do not change the original array but return a new array or value.

  • map(callbackFunction): Creates a new array by calling a function on every element of the original array.
  • filter(callbackFunction): Creates a new array with all elements that pass the test implemented by the provided function.
  • reduce(callbackFunction, initialValue): Executes a reducer function on each element, resulting in a single output value.
  • slice(startIndex, endIndex): Returns a shallow copy of a portion of an array into a new array. endIndex is exclusive.
  • concat(array2, ..., arrayN): Merges two or more arrays. Returns a new array.
  • find(callbackFunction): Returns the first element in the array that satisfies the provided testing function.
  • findIndex(callbackFunction): Returns the index of the first element that satisfies the testing function.
  • some(callbackFunction): Tests whether at least one element in the array passes the test.
  • every(callbackFunction): Tests whether all elements in the array pass the test.
  • flat(depth): Creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
  • flatMap(callbackFunction): Maps each element using a mapping function, then flattens the result into a new array (depth 1).
const nums = [1, 2, 3, 4, 5];
const doubled = nums.map(num => num * 2); // [2, 4, 6, 8, 10]
const evens = nums.filter(num => num % 2 === 0); // [2, 4]
const sum = nums.reduce((accumulator, current) => accumulator + current, 0); // 15
const subArray = nums.slice(1, 3); // [2, 3]
const moreNums = [6, 7];
const combined = nums.concat(moreNums); // [1, 2, 3, 4, 5, 6, 7]
// Using spread operator for concat: const combinedSpread = [...nums, ...moreNums];
const firstEven = nums.find(num => num % 2 === 0); // 2

In JavaScript, arrays are a special type of object. The typeof operator returns "object" for arrays.

console.log(typeof fruits); // Output: "object"

To reliably check if a variable is an array, use Array.isArray():

console.log(Array.isArray(fruits)); // Output: true
console.log(Array.isArray({a: 1})); // Output: false

While arrays are objects, they are optimized for numerically indexed access, whereas generic objects are optimized for named properties.

Spread Operator (...) and Destructuring with Arrays (ES6)

Section titled “Spread Operator (...) and Destructuring with Arrays (ES6)”

The spread operator expands an iterable (like an array) into individual elements.

const original = [1, 2, 3];
const copy = [...original]; // Creates a shallow copy
const merged = [...original, 4, 5, ...moreNums]; // Merging arrays
function sumNumbers(a, b, c) { return a + b + c; }
console.log(sumNumbers(...original)); // Spreads array elements as arguments: sumNumbers(1, 2, 3)

Allows unpacking values from arrays into distinct variables.

const [first, second, ...rest] = ["Apple", "Banana", "Cherry", "Date"];
console.log(first); // "Apple"
console.log(second); // "Banana"
console.log(rest); // ["Cherry", "Date"] (rest operator collects remaining elements)

For a complete guide to array methods, visit the MDN Array documentation.