Hi all,

I’m on step 6 of the promises module in Javascript and I have a quick question which I hope will help me understand

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);

So the function has been imported into app.js and we have declared an order array

const order = [['sunglasses', 1], ['bags', 2]];

Now what I’m struggling to understand is how the following line of code works

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

I don’t understand what item is. I understand that item[1] would be the second value in the first nested array but how is it being compared to the object property?

inventory[item[0]] is what’s thrown me, as the value of the property is not an array why are we using [0]? If I console.log(inventory[‘sunglasses’] I get the value so how is the syntax in the example working?

Sorry i speak bad english,
Array.every takes a callback function in argument, with a parameter and a condition, the parameter will be the current value of the array, and will change every time the condition is executed, if all conditions are true, then the function will return true, otherwise, false, but i don’t know how inventory[item[0]] work sorry,

You may speak bad english but I understand your point choco404.

This may or may not help Sam but I’ll type it because I understand. A different way of doing the exact same thing would be like if you made a function

const checkOrders = () => {
  item => inventory[item[0]] >= item[1]

then in your logic it would be


checkOrders might need () after it. I’m a little uncertain but basically the .every function will run each item in the order array through that function. this is what choco was trying to say. Item it turned into each object from the array in a loop fashion and then tested against the expression “inventory[item[0]] >= item[1]”. If every object passed through passes then .every will return a true else it will return a false.

item[0] of “order” is an array held inside the array of “orders”. item[0] in this case means the first object in that array which means the string value “sunglasses”. We are using the hash table of the inventory object to look up the value of the inventory property sunglasses which is 1900 to compare against the number provided in item[1] which is the second item in the array held inside the array of “orders”.

I hope that helped.

1 Like