Skip to content

ES6 - Arrays

An array in JavaScript is a special type of object used to store an ordered collection of multiple values. These values, called elements, can be of any data type (numbers, strings, objects, other arrays, etc.). JavaScript arrays are zero-indexed, meaning the first element is at index 0.

  • Scalar variables hold only one value at a time. Storing many related values would require many separate variables.
  • Managing and operating on a large set of individual variables can be cumbersome.

Arrays solve these issues by providing a structured way to store and manage lists of data.

  • Ordered Collection: Elements are stored in a specific sequence and can be accessed by their numerical index.
  • Dynamic Size: JavaScript arrays can grow or shrink dynamically; you don’t need to specify their size beforehand.
  • Heterogeneous Elements: Arrays can store elements of different data types (though it’s often good practice to keep elements of a similar type for predictability).
  • Zero-Indexed: The first element is at index 0, the second at index 1, and so on.
  • Object-Based: Arrays are a specialized type of object, with Array.prototype providing many useful methods.

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

// Array literal syntax
const emptyArray = [];
const fruits = ["Apple", "Banana", "Cherry"];
const numbers = [1, 2, 3, 4, 5];
const mixedArray = [10, "Hello", true, { name: "John" }, [6, 7]];
console.log(fruits[0]); // Apple
console.log(numbers.length); // 5

Alternatively, you can use the Array constructor:

// Using the Array constructor
const arr1 = new Array(); // Creates an empty array, same as []
const arr2 = new Array(5); // Creates an array with length 5, but elements are empty/undefined
console.log(arr2.length); // 5
console.log(arr2[0]); // undefined
const arr3 = new Array("Red", "Green", "Blue"); // Creates an array with specified elements
console.log(arr3); // ["Red", "Green", "Blue"]
// Note: If new Array() is called with a single numeric argument, it creates an array of that length,
// not an array containing that single number. This can be a source of confusion.
// For clarity, array literals `[]` are generally preferred.

Elements are accessed using their index in square brackets. You can also modify elements this way.

const colors = ["Red", "Green", "Blue"];
// Accessing elements
console.log(colors[0]); // "Red"
console.log(colors[2]); // "Blue"
console.log(colors[3]); // undefined (index out of bounds)
// Modifying elements
colors[1] = "Yellow";
console.log(colors); // ["Red", "Yellow", "Blue"]
// Adding elements by assigning to a new index
colors[3] = "Purple";
console.log(colors); // ["Red", "Yellow", "Blue", "Purple"]
// The `length` property indicates the number of elements.
console.log(colors.length); // 4

Common Array Methods (from Array.prototype)

Section titled “Common Array Methods (from Array.prototype)”

JavaScript provides a rich set of built-in methods for array manipulation:

MethodDescription
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.
shift()Removes the first element from an array and returns that element (shifts other elements down).
unshift(item1, ..., itemN)Adds one or more elements to the beginning of an array and returns the new length.
concat(array2, ..., arrayN)Returns a new array comprised of this array joined with other array(s) and/or value(s). Does not modify original arrays.
join(separator)Joins all elements of an array into a string, separated by the specified separator (default is comma).
slice(startIndex, endIndex)Returns a shallow copy of a portion of an array into a new array object. endIndex is not included. Original array is not modified.
splice(startIndex, deleteCount, item1, ..., itemN)Changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. Modifies the original array and returns an array containing the deleted elements.
indexOf(searchElement, fromIndex)Returns the first index at which a given element can be found in the array, or -1 if it is not present.
lastIndexOf(searchElement, fromIndex)Returns the last index at which a given element can be found, searching backwards.
includes(searchElement, fromIndex) (ES2016)Determines whether an array includes a certain value among its entries, returning true or false.
sort(compareFunction)Sorts the elements of an array in place. By default, sorts based on converting elements to strings and comparing their UTF-16 code unit values. Provide a compareFunction for custom sorting (e.g., for numbers).
reverse()Reverses the order of the elements of an array in place.
  • forEach(callback(element, index, array)): Executes a provided function once for each array element.
  • map(callback(element, index, array)): Creates a new array populated with the results of calling a provided function on every element in the calling array.
  • filter(callback(element, index, array)): Creates a new array with all elements that pass the test implemented by the provided function.
  • reduce(callback(accumulator, currentValue, currentIndex, array), initialValue): Executes a reducer function on each element of the array, resulting in a single output value.
  • reduceRight(...): Similar to reduce(), but processes the array from right to left.
  • some(callback(element, index, array)): Tests whether at least one element in the array passes the test implemented by the provided function.
  • every(callback(element, index, array)): Tests whether all elements in the array pass the test implemented by the provided function.
  • for...of loop (ES6): Iterates over the values of an iterable object, like an array. This is often the most straightforward way to loop through array values.
const myNumbers = [10, 20, 30];
// Using forEach
myNumbers.forEach(function(number, index) {
console.log(`forEach: Element at index ${index} is ${number}`);
});
// Using for...of (simpler for just values)
for (const number of myNumbers) {
console.log(`for...of: Element is ${number}`);
}
// Note: `for...in` loop should generally NOT be used to iterate over arrays, as it iterates over enumerable properties (including array indices and potentially inherited properties) and gives indices as strings. Use `for...of` or `forEach` for array values.
  • Array.from(arrayLikeOrIterable, mapFn, thisArg): Creates a new, shallow-copied Array instance from an array-like or iterable object (e.g., NodeList, String, Set, Map).
  • Array.of(...elements): Creates a new Array instance with a variable number of arguments, regardless of number or type of the arguments (safer than new Array() for single numeric arguments).
  • find(callback(element, index, array)): Returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.
  • findIndex(callback(element, index, array)): Returns the index of the first element in the array that satisfies the provided testing function. Otherwise, it returns -1.
  • entries(): Returns a new Array Iterator object that contains the key/value pairs for each index in the array.
  • keys(): Returns a new Array Iterator object that contains the keys (indices) for each index in the array.
  • values(): Returns a new Array Iterator object that contains the values for each index in the array.
  • Spread Syntax (...): Can be used to expand an iterable (like an array) into individual elements. Useful for creating copies, concatenating, or passing elements as function arguments.
  • Destructuring Assignment: Allows unpacking values from arrays into distinct variables.
// Array.from a string
const nameChars = Array.from('Hello');
console.log(nameChars); // ['H', 'e', 'l', 'l', 'o']
// Array.of
const singleNumArray = Array.of(7);
console.log(singleNumArray); // [7]
// find and findIndex
const inventory = [
{ name: 'apples', quantity: 2 },
{ name: 'bananas', quantity: 0 },
{ name: 'cherries', quantity: 5 }
];
const cherryItem = inventory.find(item => item.name === 'cherries');
console.log(cherryItem); // { name: 'cherries', quantity: 5 }
const bananaIndex = inventory.findIndex(item => item.name === 'bananas');
console.log(bananaIndex); // 1
// entries, keys, values (using for...of with iterator)
const letters = ['a', 'b', 'c'];
for (const [index, value] of letters.entries()) {
console.log(`Index: ${index}, Value: ${value}`);
}
// Output: Index: 0, Value: a ... etc.
// Spread Syntax
const arrA = [1, 2];
const arrB = [3, 4];
const combined = [...arrA, 0, ...arrB, 5];
console.log(combined); // [1, 2, 0, 3, 4, 5]
const copyArrA = [...arrA]; // Shallow copy
// Destructuring Assignment
const [first, second, , fourth] = [10, 20, 30, 40];
console.log(first); // 10
console.log(second); // 20
console.log(fourth); // 40 (30 is skipped)

JavaScript does not have true multi-dimensional arrays in the C++/Java sense, but you can create arrays of arrays to achieve similar functionality.

const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
console.log(matrix[0][0]); // 1 (first row, first column)
console.log(matrix[1][2]); // 6 (second row, third column)

Arrays are a cornerstone of data manipulation in JavaScript, offering flexibility and a powerful set of methods for various tasks.