Skip to the workspace
Pebellslearn by building
Data Structures  ›  Lesson

Arrays

Arrays 12 min

javascript / Arrays

Explore each scene at your own pace.

01 · Arrays

Arrays

Arrays

An array is an ordered collection indexed from zero. Its length counts positions, and methods such as push can change its contents.

A reading list keeps an order; the first article is at index 0, not 1.

See the mechanism

Walk through the modelArraysAuthored snapshots of the example; use Run below to test the code.
index 0"Morning"
index 1"Night"
length2
Indices count from zero.
1 of 3

Follow one example

javascript

Index 0 reads "Morning". push appends a third value, so length becomes 3 and the new value is at index 2. The const binding still names the same array. Reading beyond its populated entries returns undefined; it does not automatically wrap to the beginning. Arrays can be sparse, so do not equate every index below length with a present value. filter keeps the 4- and 2-minute entries; map transforms every entry into seconds; reduce combines them into total 14 using initial accumulator 0. These operations return results; their callbacks here do not mutate the source array. Supplying 0 makes reducing an empty array well-defined.

Predict, change and check

Predict: After appending one item, what are the last index and the length?

Test your explanation: Append another title, then print titles[titles.length - 1]. Try the empty array and explain why index -1 does not read a last item with bracket syntax.

The tasks below ask you to explain that result and apply the idea to different inputs.

Apply and distinguish

Choose transformation or mutation deliberately

map, filter and reduce return results with different meanings: transform each entry, select entries, or accumulate a result. A callback can still mutate shared objects, so calling map is not a guarantee of a pure operation. Sort mutates an array; copy before sorting when the original order must remain available.

A default sort compares string representations, so numeric order needs an appropriate comparator. An empty reduce without an initial accumulator throws. Sparse arrays can have a length larger than their number of present entries. Compare an ordinary dense list with a deliberately sparse one before assuming every index below length contains a supplied value.

Check your understanding: State the input contract, identify the operation that changes the result, and give one boundary input that would distinguish the correct rule from the mistake described above.

Scene 1 of 2
Project context and further resources
Additional resources
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.