Let's combine arrays and functions into a little shopping list program.
const shoppingList = [];
function addItem(item) {
if (shoppingList.includes(item)) {
console.log(`⚠️ "${item}" is already on the list.`);
return;
}
shoppingList.push(item);
console.log(`✅ Added "${item}".`);
}
function removeItem(item) {
const index = shoppingList.indexOf(item);
if (index === -1) {
console.log(`❓ "${item}" isn't on the list.`);
return;
}
shoppingList.splice(index, 1);
console.log(`🗑️ Removed "${item}".`);
}
function printList() {
console.log("------ SHOPPING LIST ------");
if (shoppingList.length === 0) {
console.log("(empty, time to go home!)");
return;
}
for (let i = 0; i < shoppingList.length; i++) {
console.log(`${i + 1}. ${shoppingList[i]}`);
}
console.log(`(${shoppingList.length} items)`);
}
addItem("tomatoes");
addItem("onions");
addItem("rice");
addItem("onions");
addItem("palm oil");
removeItem("plantain");
removeItem("onions");
printList();
It prints
✅ Added "tomatoes". ✅ Added "onions". ✅ Added "rice". ⚠️ "onions" is already on the list. ✅ Added "palm oil". ❓ "plantain" isn't on the list. 🗑️ Removed "onions". ------ SHOPPING LIST ------ 1. tomatoes 2. rice 3. palm oil (3 items)
Notice how each function has one clear job, and they all share the same shoppingList array. This is the beginning of how real apps are structured: some data, plus functions that work with it.
Add a function sortList() that sorts the list alphabetically, and a function clearList() that empties the whole list. (Hint for clearing: you can't reassign a const, but you can set shoppingList.length = 0, or use splice(0).)
Arrays: conquered! You can now store whole lists of things and work with them. In Grade 8, we'll learn the other great way to organize data. Instead of a numbered list, we'll describe things using labeled details. Say hello to objects.