Link to home
Start Free TrialLog in
Avatar of Bruce Gust
Bruce GustFlag for United States of America

asked on

Am I explaining this "find" function correctly?

Here's the code:

module.exports = class Cart {
  static addProduct(id) {
    //fetch the previous cart
    fs.readFile(p, (err, fileContent) => {
      let cart = {products: [], totalPrice: 0}
      if(!err) {
        cart = JSON.parse(fileContent);
      }
    });
    //analyze the cart => find existing product
    [b]const existingProduct = cart.products.find(prod=>prod.id===id);[/b]
    //add new product / increase quantity
  }
};

Open in new window


I'm using this as my academic starting point in order to understand why this works: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find

...tell me if I'm explaining this correctly.

existingProduct is a variable that's either going to return the matching product id or "undefined" based on whether or not the "id" that's being evaluated matches anything in the already existing products array which is a property belonging to the "cart" object.

This:

cart.products.find(prod=>prod.id===id);

Open in new window


...is akin to this:

for(products as prod) {
   if(prod.id=id)
    {
       //we've got a match
    }
    else
    {
          //undefined...
    }
}

Is that right? And if not, what am I missing?
ASKER CERTIFIED SOLUTION
Avatar of Kelvin McDaniel
Kelvin McDaniel
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Bruce Gust

ASKER

Thanks Kelvin! That answered my question!
You're welcome. 😊