DevPath · Learn to code ESPTEN

Arrays and their methods

Creating arrays, indices and length

What is an array?

Almost everything you see in an app is a list: the products in a store, the messages in a chat, the songs in a playlist, the results of a search. All of those are arrays, and mastering them is half the battle won.

An array (list) is an ordered collection of values stored under a single name. Think of it as a row of numbered lockers, each one with a value inside.

Creating an array

const fruits = ["apple", "pear", "grape"];
const numbers = [10, 20, 30];
const empty = [];

An array can contain any type of data, even mixed.

Access by index

Each element has a position or index, which starts at 0:

console.log(fruits[0]); // "apple"
console.log(fruits[2]); // "grape"
console.log(fruits[9]); // undefined (doesn't exist)

You can modify an element by assigning to its index:

fruits[1] = "banana";

The length property

length indicates how many elements there are:

console.log(fruits.length); // 3

A common trick: the last element is at array[array.length - 1].

Examples

Accessing the first and last element

const colors = ["red", "green", "blue"];
console.log(colors[0]);                    // "red"
console.log(colors[colors.length - 1]);   // "blue"
console.log("There are", colors.length, "colors");
Put this into practice

DevPath is a hands-on course: you read the theory here; in the app you put it into practice with exercises that really run, offline.

Start free in the app →
Adding, removing and slicing →