Node.js - Getting Started with for loop

by
Jeremy Canfield |
Updated: September 09 2024
| Node.js articles
Here is an example of how you create a list of fruit. Check out my article FreeKB - Node.js - Getting Started with Lists for more details on Lists / Arrays.
length can be used to count the number of elements in the list.
const fruits = ["Apple", "Orange", "Banana", "Pineapple"]
console.log(`There are ${fruits.length} elements in the 'fruits' list`)
Which in this example should return 4.
~]$ node app.js
There are 4 elements in the 'fruits' list
With the length in hand, you can loop through each element in the list.
const fruits = ["Apple", "Orange", "Banana", "Pineapple"]
for ( let i = 0; i < fruits.length; i++ ) {
console.log(fruits[i]);
}
Or using forEach.
const fruits = ["Apple", "Orange", "Banana", "Pineapple"]
fruits.forEach(item => {
console.log(item)
})
Which should return the following.
Apple
Orange
Banana
Pineapple
Did you find this article helpful?
If so, consider buying me a coffee over at