Indexes and length
Pick single items out of an array.
1const fruits = ["apple", "banana", "cherry"];
2console.log(fruits[0]);
3console.log(fruits.length);
4console.log(fruits[fruits.length - 1]);
$ node main.js
apple
3
cherry
Every line, explained
const fruits = ["apple", "banana", "cherry"];- An array stores several values in one variable. The values go between square brackets, separated by commas.
console.log(fruits[0]);- You get one item using its index (position) in square brackets, and counting starts at 0, not 1! fruits[0] is "apple", fruits[1] is "banana", fruits[2] is "cherry".
console.log(fruits.length);- .length tells you how many items the array holds: here, 3.
console.log(fruits[fruits.length - 1]);- A classic trick for the LAST item: the last index is always length minus 1 (3 items โ indexes 0, 1, 2). So fruits[fruits.length - 1] is "cherry".