JavaScript arrays are the first data structure that you reach for, and they are also the one that people misuse most often. This crash course shows you what an array really is while the program is running, how to read items out of it without tripping over undefined, and the small number of traps that catch almost every beginner.
This is the first lesson in the JavaScript Array Methods module, and the next lesson in this module is about "Changing Arrays: push, pop, splice and More".
What is a JavaScript array, really?
An array is an ordered list of values with a numeric index and a length. You almost always create one with a literal, which means square brackets, the values, and commas between them. Inside the brackets you can put anything at all. Strings, numbers, objects, and even other arrays are all allowed, and JavaScript will not complain about any of it. That permissiveness is convenient when you are grouping things together, and it is dangerous for the rest of this module, because the array itself promises nothing about the shape of the things that it holds.
The important detail is what happens under the hood. An array in JavaScript is a special kind of object. Its keys are the text versions of the indices, and it also has a length property. The array methods that you will meet in this module are not built into the array itself. push, map, and filter live on Array.prototype, which is the shared prototype that every array inherits from. That is why typeof reports object, and it is also why you can technically hang your own properties on an array without causing an error.
const posts = [
{ title: 'Closures', minutes: 12 },
{ title: 'Arrays', minutes: 9 },
{ title: 'Promises', minutes: 15 },
];
console.log(posts.length); // 3
console.log(posts[0].title); // Closures
console.log(posts.at(-1).title); // Promises
console.log(posts[3]); // undefined
console.log(posts[-1]); // undefined
Those last two lines are the ones that people miss when an array bug looks like a data bug. Reading past the end of an array does not throw an error. It quietly hands you undefined instead. And posts[-1] is also undefined, because a negative index is not a JavaScript idea for bracket access. The property that is named -1 simply does not exist on the object. The at() method was added so that you can count from the end without doing the arithmetic yourself, and it is the clearest way to grab the last item.
How do you read every item out of an array?
Reading one item is simple. Reading all of them is where your style choice shows. The for...of loop walks the values in order and hands each one to a variable that you declare with const or let. It is the loop to reach for when you want to look at each value and do something with it, because it has an obvious place to put break and continue, which the callback-based array methods famously do not give you.
const steps = ['plan', 'write', 'edit', 'publish'];
for (const step of steps) {
console.log('> ' + step);
}
console.log(steps.join(' -> '));
That prints four lines that begin with >, and then it prints the joined list plan -> write -> edit -> publish. The join method turns an array into a string using a separator that you choose, and that is the quickest way to render a list into a sentence, into a breadcrumb trail, or into a list of comma-separated names.
Why does typeof say object for an array?
Because an array really is one. The only reliable way to test for an array is Array.isArray(). It returns true for real arrays, and it returns false for array-like objects such as the arguments object or a NodeList. Those objects have a length and they have indexed properties, but they are not arrays, so they do not have the array methods.
const tags = ['js', 'web', 'node'];
console.log(typeof tags); // object
console.log(Array.isArray(tags)); // true
console.log(Array.isArray({ 0: 'a', length: 1 })); // false
Is length just a number that you read?
length is special, because it is writable. Assigning to it reshapes the array straight away. Setting it to a smaller number deletes everything beyond that point. Setting it to a larger number creates holes, which are empty slots that read as undefined but still take up a position and still count towards the length.
const queue = ['a', 'b', 'c'];
queue.length = 1;
console.log(queue); // [ 'a' ]
console.log(queue[2]); // undefined
const sparse = ['a', 'b'];
delete sparse[1];
console.log(sparse.length); // 2
console.log(sparse[1]); // undefined
console.log(JSON.stringify(sparse)); // ["a",null]
Look at the last line. The delete operator leaves a hole instead of closing the gap, so the array still reports a length of 2 and JSON.stringify turns the hole into null. Holes are nearly always an accident rather than a decision, and that is why the rest of this module leans on filter and slice instead of delete.
Which array traps catch beginners most often?
Three of them, in rough order of how often they cause trouble. The first one is assuming that the indices are contiguous. They are not guaranteed to be, so code that reads items[0] through items[items.length - 1] can meet undefined when an array contains a hole. The second one is treating an array like an object with named keys. It works, and then for...of quietly ignores your named keys, because for...of only walks the indexed values. The third one is forgetting that arrays are mutable references. Handing an array to a function gives that function a pointer, so a function that pushes into the array changes the array that you passed in. That third trap explains a lot of confusing bugs, and it is the same rule that governs objects, so the objects module picks it up in full.
How do you build an array when you have no literal?
Array.of() takes its arguments as the items. Array.from() takes something you can iterate over, such as another array, a Set, or a string, and it accepts an optional function that transforms each item as the new array is built. It also accepts objects that merely have a length, which is how you create a fixed-size array of placeholders without writing a loop.
const scores = Array.of(1, 2, 3);
console.log(scores); // [ 1, 2, 3 ]
const doubled = Array.from([1, 2, 3], function (number) {
return number * 2;
});
console.log(doubled); // [ 2, 4, 6 ]
const placeholders = [];
for (let index = 0; index < 3; index++) {
placeholders.push(index);
}
console.log(placeholders); // [ 0, 1, 2 ]
What is worth memorising before the next lesson?
Here is the deliberately short version, and each row gets its own lesson in this module.
| Expression | What it does | Watch out |
|---|---|---|
arr.length | Number of indexed slots | Writable; assigning truncates or extends the array |
arr[i] | Reads the item at index i | undefined past the end; negative indices do not work |
arr.at(i) | Reads by index, negative values count from the end | ES2022, so older browsers will not have it |
Array.isArray(x) | The only reliable array test | typeof will not do it |
for...of | Walks the values in order | Skips holes entirely |
Try it yourself: make a file called reading-list.js and put an array of five objects into it, where every object has a title and a minutes number. Print the title of the first item with list[0].title, print the title of the last one with list.at(-1).title, and print the total minutes with a for...of loop that adds to a running total. Then push a sixth item onto the end and print the new length. Finally, set list.length = 5 and print the length again. The sixth item should vanish without you deleting anything yourself.