Menu
Coddy logo textTech

View List

Part of the Fundamentals section of Coddy's JavaScript journey — lesson 74 of 77.

challenge icon

Challenge

Easy

Now, add a function named viewList that gets no arguments and prints the grocery list.

The function will output:

Grocery List:
1. Milk
2. Eggs
3. Butter

For a list with the following items ["Milk", "Eggs", "Butter"].

If the list is empty output:

The grocery list is empty.

 

 

Add the following code at the end of your code to test it (instead of the previous testing code):

viewList();
addItem("Milk");
addItem("Bread");
addItem("Eggs");
viewList();
removeItem("Bread");
viewList();
removeItem("Cheese");

Try it yourself

// Grocery list array
let groceryList = [];

// Function to add an item to the grocery list
function addItem(item) {
	groceryList.push(item);
	console.log(`${item} added to the grocery list.`);
}

// Function to remove an item from the grocery list
function removeItem(item) {
	const index = groceryList.indexOf(item);
	if (index !== -1) {
		groceryList.splice(index, 1);
		console.log(`${item} removed from the grocery list.`);
	} else {
		console.log(`${item} is not in the grocery list.`);
	}
}

addItem("Milk");
addItem("Bread");
addItem("Eggs");
removeItem("Bread");
removeItem("Cheese");

All lessons in Fundamentals