Arrays Fundamentals
Arrays are one of the most fundamental data structures in JavaScript. They allow you to store multiple values in a single variable. Let's dive deep into how they work.
1. Creating Arrays
There are several ways to create arrays in JavaScript:
Array Literal Syntax
The most common and recommended way to create an array is using array literals [].
const fruits = ['Apple', 'Banana', 'Orange'];
const mixed = [1, 'Two', true, null, { key: 'value' }];
The Array Constructor
You can also use the new Array() constructor, though it has some quirks.
const emptyArray = new Array(); // []
const lengthArray = new Array(5); // Creates an array with 5 empty slots [empty × 5]
const prefilledArray = new Array(1, 2, 3); // [1, 2, 3]
2. Indexing and length
Arrays are zero-indexed, meaning the first element is at index 0.
const colors = ['Red', 'Green', 'Blue'];
console.log(colors[0]); // 'Red'
console.log(colors[2]); // 'Blue'
The length Property
The length property returns the number of elements in the array. Interestingly, in JavaScript, length is writable.
const numbers = [10, 20, 30, 40, 50];
console.log(numbers.length); // 5
// Truncating an array
numbers.length = 3;
console.log(numbers); // [10, 20, 30]
// Clearing an array
numbers.length = 0;
console.log(numbers); // []
3. Sparse Arrays and Holes
JavaScript arrays are technically objects where indices are keys. This means an array doesn't have to be contiguous. When an array has missing elements, it is called a sparse array.
const sparse = [];
sparse[0] = 'a';
sparse[5] = 'f';
console.log(sparse); // ['a', empty × 4, 'f']
console.log(sparse.length); // 6
console.log(sparse[2]); // undefined
Note: Array methods like forEach, map, and filter typically skip these empty holes, which can lead to unexpected behavior. It is best to avoid sparse arrays.
4. Modern Creation Methods: Array.from() and Array.of()
ES6 introduced two powerful static methods for array creation to address shortcomings of the Array constructor.
Array.of()
Array.of() creates a new array instance with a variable number of arguments, regardless of number or type of the arguments. This solves the quirk where new Array(5) creates 5 empty slots instead of [5].
const arr1 = Array.of(7); // [7]
const arr2 = Array.of(1, 2, 3); // [1, 2, 3]
Array.from()
Array.from() creates a new, shallow-copied Array instance from an array-like or iterable object (like NodeList, Set, Map, or strings).
// From a string
const chars = Array.from('hello');
// ['h', 'e', 'l', 'l', 'o']
// From a Set
const set = new Set(['foo', 'bar', 'foo']);
const uniqueArray = Array.from(set);
// ['foo', 'bar']
// Using the mapping function
const numbers = [1, 2, 3];
const doubled = Array.from(numbers, x => x * 2);
// [2, 4, 6]
Array.from() is especially useful for generating arrays of specific lengths:
const sequence = Array.from({ length: 5 }, (_, index) => index + 1);
// [1, 2, 3, 4, 5]