Understand the idea

An array stores an ordered collection of values. Indexing starts at 0. For a dense array such as the example, length is the number of items; sparse arrays can contain empty slots, so length is not always the count of actual entries.

filter creates a new array containing values that pass a test. map creates a new array by transforming each value. These operations do not directly change the original array, although objects inside the arrays may still be shared references.

Read the example

This is a JavaScript fragment. Run it in a browser console or an external script. Supply any HTML or data file named in the example first.

JavaScript · EXAMPLE
const places = ["Erfurt", "Berlin", "Amsterdam"];
const shortNames = places.filter(place => place.length < 7);
console.log(shortNames); // ["Erfurt", "Berlin"]
console.log(places.length); // 3

A small mistake, explained

What goes wrong

Using array.length as the last index goes one place beyond the final item.

How to fix it. The last index is length - 1. Handle the empty-array case, which has no final item.

Try it yourself

Add another city and change the filter condition. Check that places still contains the complete collection.

Further reading

ECMAScript — Array.prototype.filter

Original explanation and example prepared for HTML code FYI with AI assistance. Test the code in your own context. How these guides are made.