JavaScript Arrays
An array is a list of values in order. An index is the numbered position of one value in the list.
Read by index
An array is a list of values in order, and this literal holds three fruits. The reads below pick items by their index positions.
const fruits = ["Apple", "Pear", "Plum"];
console.log(fruits[0]);
console.log(fruits[2]);Count and change
The length line counts the items in this array. The assignment then swaps the item at index 1.
const fruits = ["Apple", "Pear", "Plum"];
console.log(fruits.length);
fruits[1] = "Mango";
console.log(fruits);Check and grow
typeof and Array.isArray answer two different questions here. The last assignment adds Kiwi at index 3.
const fruits = ["Apple", "Pear", "Plum"];
console.log(typeof fruits);
console.log(Array.isArray(fruits));
fruits[3] = "Kiwi";
console.log(fruits);Example
const fruits = ["Apple", "Pear", "Plum"];
console.log(fruits[0]);
console.log(fruits.length);
fruits[0] = "Mango";
fruits[3] = "Kiwi";
console.log(fruits);
console.log(Array.isArray(fruits));Key points
- An index counts from 0, so the first item sits at index 0.
- Square brackets mark the start and end of an array literal.
- length: the count of items in an array
- Declaring an array with const still allows its items to change.
- An assignment to a new index adds an item at that position.
In this example, the fruits array starts with three items. The first log reads the item at index 0, and the second logs the length, 3. An assignment swaps the first item for Mango, and another assignment adds Kiwi at index 3. The last lines log the four-item array and confirm it is an array.
Note
typeof an array says "object", and Array.isArray gives the reliable check.
Try it Yourself
Edit the code, then press Run.
Runs in your browser — the preview under the editor is the real result. Nothing is sent to a server. The code runner panel (right) does the same with more room.
Exercise
Which index holds the first item of an array?