0
0
Javascriptprogramming~15 mins

Reduce method in Javascript - Mini Project: Build & Apply

Choose your learning style9 modes available
Sum of Prices Using the Reduce Method
πŸ“– Scenario: You are managing a small online store. You have a list of products with their prices. You want to find out the total price of all products combined.
🎯 Goal: Build a program that uses the reduce method to calculate the total price of all products in the list.
πŸ“‹ What You'll Learn
Create an array of product objects with exact names and prices
Create a variable to hold the initial total price
Use the reduce method with a callback function to sum all product prices
Print the final total price
πŸ’‘ Why This Matters
🌍 Real World
Calculating totals is common in shopping carts, budgets, and reports.
πŸ’Ό Career
Knowing how to use reduce helps in data processing and summarizing information efficiently.
Progress0 / 4 steps
1
Create the products array
Create an array called products with these exact objects: { name: 'Book', price: 15 }, { name: 'Pen', price: 5 }, { name: 'Notebook', price: 10 }.
Javascript
Need a hint?

Use square brackets [] to create an array and curly braces {} for each product object.

2
Create the initial total variable
Create a variable called initialTotal and set it to 0.
Javascript
Need a hint?

Use const to create a variable that holds the starting total price.

3
Use reduce to calculate total price
Create a variable called totalPrice and set it to the result of calling products.reduce with a callback function that adds the current product's price to the accumulator. Use initialTotal as the starting value.
Javascript
Need a hint?

The reduce method takes a function with two parameters: the accumulator and the current item. Add the current product's price to the accumulator.

4
Print the total price
Write a console.log statement to print the value of totalPrice.
Javascript
Need a hint?

Use console.log(totalPrice) to show the total price in the console.