Need help in walking through what happens with one line of code?


I am working on this exercise and I am not sure I completely understand what the ** bolded ** line of code is doing in the library. js file?

I believe .every() checks the order against what is in inventory… but I am not clear as to how that happens talking myself through the code. I guess I am asking for help with walking through what is happening.

const inventory = {
sunglasses: 1900,
pants: 1088,
bags: 1344

const checkInventory = (order) => {
return new Promise((resolve, reject) => {
setTimeout(() => {
let inStock = order.every(item => inventory[item[0]] >= item[1]);
if (inStock) {
resolve(Thank you. Your order was successful.);
} else {
reject(We're sorry. Your order could not be completed because some items are sold out.);
}, 1000);

module.exports = { checkInventory };

This is the lesson:

Thank you!

order is assumed to be an array since it is the only object with an .every() method.

The .every() method is an iterator that takes a callback function as its argument.

item => inventory[item[0]] >= item[1]

The above is a concise body arrow function where item is the iterator variable. In each iteration, the inventory quantity is checked for each item in the order array.

1 Like

Thank you for taking the time to address my question.

In app.js file the array is order = [[‘sunglasses’, 1], [‘bags’, 2]]; so this would mean that in the first iteration item => inventory[item[0]] >= item[1] would be:

[‘sunglasses’, 1] => inventory[sunglasses: 1900] >= item[1]

And in second iteration:

[‘bags’, 2] => inventory[bags: 1344] >= item[1]


1 Like

I can’t see the exercise, but if as you said order = [[‘sunglasses’, 1], [‘bags’, 2]]; , then if we iterate over this array:

  • First iteration item will be ['sunglasses', 1], item[0] will be 'sunglasses' and item[1] will be 1.
    inventory[item[0]] will become inventory['sunglasses'] and the comparison 1900 >= 1 will be made.

  • Second iteration item will be ['bags', 2], item[0] will be 'bags' and item[1] will be 2.
    inventory[item[0]] will become inventory['bags'] and the comparison 1344 >= 2 will be made.

let inStock = order.every(item => inventory[item[0]] >= item[1]);

We will iterate through all entries in the order array one entry at a time. If the inventory of the item is greater or equal than the ordered quantity, then the entry will pass the test. If any of the entries fails this test, then inStock will be false. If every entry passes the test, then inStock will be true.

1 Like