Register to get access to free programming courses with interactive exercises

Checking a value exists JS: Arrays

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.

Get access
130
courses
1000
exercises
2000+
hours of theory
3200
tests

Sign up

Programming courses for beginners and experienced developers. Start training for free

  • 130 courses, 2000+ hours of theory
  • 1000 practical tasks in a browser
  • 360 000 students
By sending this form, you agree to our Personal Policy and Service Conditions

Our graduates work in companies:

Bookmate
Health Samurai
Dualboot
ABBYY