If variables are boxes, then an array is a row of boxes. We can put anything we want in an array. Arrays can contain any number of values.
For this lesson, don't worry about understanding all of the example code. I just want you to get a feel for how arrays work.
Use Case
Arrays are used to represent lists of values. We can perform actions on the individual items in the array.
Here's an example of how useful arrays are. Imagine we have a flower garden, and we want to count the number of roses in the garden. We can use a function like this:
function countRoses(flower1, flower2, flower3) {
// count the number of arguments that equal "rose"
// return the count
}
As you can see, this function can only handle 3 flowers. Each flower is hard-coded as a specific argument. The function can't handle any more or any fewer.
If we had an array of flowers, we could use that instead:
function countRoses(flowers) {
// go through all values in the array
// count up the ones that equal "rose"
// return the count
}
Now we can handle any number of flowers, from zero to hundreds of flowers or more.
Here's a complete example you can run in the editor:
function countRoses(flowers) {
let count = 0;
for (let i = 0; i < flowers.length; i++) {
if (flowers[i] === 'rose') {
count++;
}
}
return count;
}
const myFlowers = ['rose', 'tulip', 'lily', 'rose', 'rose', 'lily', 'tulip', 'rose'];
const roseCount = countRoses(myFlowers);
console.log(roseCount);