View List
Part of the Fundamentals section of Coddy's JavaScript journey — lesson 74 of 77.
Challenge
EasyNow, 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. ButterFor 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
4Operators Part 2
Logical Operators Part 1Logical Operators Part 2Recap - Simple LogicLogical Operators Part 3Type Coercion7Bill Split Calculator
Welcome MessageCalculating The Tip And Total2Variables
NumbersStringBooleanNaming ConventionsEmpty VariablesRecap - Initialize VariablesConstants3Operators Part 1
Arithmetic OperatorsModulo OperatorArithmetic ShortcutsComparison OperatorsStrict vs Loose EqualityRecap - Simple Math6Basic IO
OutputOutput with VariablesType Conversion - Part 1Type Conversion - Part 2Recap - Till 120Recap - True or False