Question
How do you find out how many elements an array has, and how do you visit each one?
Answer
The .length property gives the element count, and a loop from index 0 up to length - 1 lets you visit each element in turn.
Every array carries a .length property holding its current number of elements. Combined with a loop, this lets you process an array of any size without knowing the count in advance:
let animals = ['lion', 'rat', 'fish', 'crocodile'];
let i = 0;
while (i < animals.length) { // note: < length, since the last index is length - 1
console.log(animals[i]);
i = i + 1;
}
Because indices run from 0 to length - 1, the condition uses < (not <=); using <= would step one past the end and read undefined.
A cleaner, modern way to do the same thing is the for...of loop, which hands you each element directly so there's no index to manage:
for (let animal of animals) {
console.log(animal);
}
Arrays also come with handy built-in methods, for example: push(item) adds to the end, pop() removes from the end, shift() removes from the start, and includes(item) tells you whether a value is present.
Note saved — thanks!