Skip to content
AgileLogics

Programming glossary

Array

An ordered collection of values, accessed by numbered position (usually starting at 0).

Imagine a row of numbered lockers at a train station. Each locker holds one item, and you can reach any item instantly by its number instead of opening every door. Arrays organise data the same way. Instead of creating separate variables called day1, day2 and day3, you keep all the values in one container and refer to each by its index.

Example

const temps = [18, 21, 19, 24];

console.log(temps[0]);                // 18 (first item)
console.log(temps.length);            // 4
console.log(temps[temps.length - 1]); // 24 (last item)

temps.push(22);   // add to the end
temps[1] = 20;    // replace the second item
console.log(temps); // [18, 20, 19, 24, 22]

Declaring with const stops the name temps from being pointed at a different array, but the contents can still change.

Why indexes usually start at zero

In C and the many languages influenced by it, an index is really an offset from the start of the array, so the first element sits at offset 0. JavaScript, Python, Java, PHP and Go all follow this convention. A few languages count from 1 instead, including Lua, R and MATLAB, so check when you pick up a new one. Asking for a position past the end is a classic bug: Java throws an exception, while JavaScript quietly returns undefined.

Array vs list

Terminology varies between languages. In Java, an array has a fixed length chosen when it is created, while an ArrayList can grow. Python's everyday sequence type is called a list, and it grows or shrinks freely. PHP's "arrays" are really ordered maps that accept text keys as well as numbers. JavaScript arrays resize automatically and can even mix types, holding numbers and strings side by side.

Learn more

Last updated