Project: summarize inventory records
Quick answer
An inventory can be an array of objects containing quantity and price. A loop can summarize the records without losing their field names.
How it works
For trusted records with nonnegative integer quantity and price in minor units, accumulate units and total value separately. Count records with zero quantity as out of stock. Return a named summary object. Bound input sizes so results stay safe integers.
function summarize(items) { let units = 0; let value = 0; let empty = 0; for (const item of items) { units += item.quantity; value += item.quantity * item.price; if (item.quantity === 0) empty++; } return { units, value, empty }; }console.log(JSON.stringify(summarize([{quantity:2,price:5},{quantity:0,price:9}])));Expected output in Node.js:
{"units":2,"value":10,"empty":1}The named result distinguishes physical counts and monetary value. JSON.stringify prints a compact object representation.
function valueOf(items) { let total = 0; for (const item of items) total += item.quantity * item.price; return total; }console.log(valueOf([]), valueOf([{quantity:3,price:4}]));Expected output in Node.js:
0 12Zero is the identity for addition and the result for empty stock.
Common mistakes
Count out-of-stock records separately from total units. The result is not an accounting system; validate real inputs and currency rules separately.
Practice
Test empty inventory, all-zero quantities and mixed records; verify input remains unchanged.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Project: summarize inventory records — Knowledge Check
Apply the taught concept and reason about the result.
For one record {quantity:3,price:4}, what is its inventory value?
What should the total units for an empty inventory be in this project?
For quantities 0, 2 and 0, how many records are out of stock?
Why return a named summary object for units and value?
Why bound quantity, price and record count in an integer-unit exercise?