Node.js - Getting Started with Lists

by
Jeremy Canfield |
Updated: September 09 2024
| Node.js articles
Here is an example of how you create a list of fruit.
const fruits = ["Apple", "Orange", "Banana", "Pineapple"];
console.log(fruits);
Running this Node.js app should return something like this.
~]$ node app.js
[ 'Banana', 'Orange', 'Apple', 'Mango' ]
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
You can use an index number to do something with a specific element in the list.
const fruits = ["Apple", "Orange", "Banana", "Pineapple"];
console.log(`index 0 = ${fruits[0]}`);
console.log(`index 1 = ${fruits[1]}`);
console.log(`index 2 = ${fruits[2]}`);
console.log(`index 3 = ${fruits[3]}`);
Which should return the following.
index 0 = Apple
index 1 = Orange
index 2 = Banana
index 3 = Pineapple
You can loop through each element in the list. For more details on for loops, check out my article FreeKB - Node.js - Getting Started with for loop.
const fruits = ["Apple", "Orange", "Banana", "Pineapple"];
fruits.forEach(item => {
console.log(item)
}
Which should return the following.
Apple
Orange
Banana
Pineapple
push can be used to append an item to a list.
const fruits = ["Apple", "Orange", "Banana", "Pineapple"];
fruits.push("Strawberry")
Did you find this article helpful?
If so, consider buying me a coffee over at