When working with arrays, a situation called an “array overrun” can often take place. It occurs when a non-existent index is accessed:
const animals = ['cats', 'dogs', 'birds'];
// Item with index 5 does not exist
animals[5]; // undefined
Depending on the programming language, array overruns can be treated in various ways. Sometimes, an error occurs, sometimes not, and every so often this kind of output returns random data from an adjacent memory block, as in C, which can lead to disaster.
JavaScript has its own way. Great freedom is given here, allowing you to take almost any liberty. Accessing a non-existent index will return undefined
. In this case, no errors occur, it's seen as a perfectly normal situation:
const animals = ['cats', 'dogs', 'birds'];
// Array overrun
animals[5]; // undefined
animals[4]; // undefined
animals[3]; // undefined
// Hooray, we hit the array's boundaries :)
animals[2]; // 'birds'
In the vast majority of situations, array overrun is best avoided. It usually happens because of logic errors in the program. The program, however, may continue to work and might even sometimes give the correct result. The easiest way to check for an overrun is to make sure that the index does not exceed the length of the array:
// It's important to use <, not <=.
// because there is no such index as items[items.length]
if (index < items.length) {
items[index]; // everything is great!
}
Over time, you'll learn to see these situations and fix them fairly quickly. But even experienced programmers regularly make mistakes when dealing with arrays.
For full access to the course you need a professional subscription.
A professional subscription will give you full access to all Hexlet courses, projects and lifetime access to the theory of lessons learned. You can cancel your subscription at any time.