01 / 04
Loops, and where your data lives
INPUT · Slides
Using the length of an array
02 / 04
.length tells you the number
Write .length after an array and you get how many items are in it right now.
Counting becomes the array's job rather than yours.
const fruits = ["apple", "orange", "peach"];console.log(fruits.length);Result
3
03 / 04
Use it in the loop condition
Swap the 3 in i < 3 for fruits.length and you get a repetition that runs correctly however many items there are.
This is the finished form for pairing for with an array. You will write it many times.
const fruits = ["apple", "orange", "peach", "pear"];for (let i = 0; i < fruits.length; i++) { console.log(fruits[i]);}Result
apple orange peach pear
04 / 04
The last item is length - 1
Because numbering starts at 0, the last number is one less than length.
Three items means length is 3 and the last number is 2. Write list[list.length - 1] and you get the last item whatever the length.
const list = ["a", "b", "c"];console.log(list.length);console.log(list[list.length - 1]);Result
3 c