'Why is my else block is executing when if block condition is true in javascript

So i was learning node js in which i got stuck why is my cartData.json file is not ipdating properly. Below is the code snippet :-

routes.post("/cart", (req, res, next) => {
  let prodId = req.body.productId;
  let productList = [];
  let cartList = [];
  fs.readFile(productListDatapath_dir, (err, data) => {
    if (!err) productList = JSON.parse(data);
  });

  fs.readFile(cartListDatapath_dir, (err, data) => {
    if (!err) {
      cartList = JSON.parse(data);
      cartList.forEach((product) => {
        prodId = prodId.replace(/\s+/g, " ").trim();
        if (product.Id === prodId) {
          console.log("If block executed");
          product.quantity += 1;
        } 
        else 
        {
          console.log("else block executed");
          productList.forEach((element) => {
            prodId = prodId.replace(/\s+/g, " ").trim();
            if (element.Id === prodId) {
              element.quantity = 1;
              cartList.push(element);
            }
          });
        }
        // res.render("./shop/product-detail.ejs", { title: "Product Details", product, });
      });
    }
    // Writing the content of temporary array into the productData.json file
    fs.writeFile(cartListDatapath_dir, JSON.stringify(cartList), (err) => {
      console.log(err);
    });
  });
  res.redirect("/cart");
});
module.exports = routes;

Below is the Json data present in the cart list :-

[
  {
    "title": "camera",
    "imageUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1280px-Image_created_with_a_mobile_phone.png",
    "description": "girl clicking picture",
    "amount": "1254",
    "Id": "12345",
    "quantity": 1
  },
  {
    "title": "Mountain Picture",
    "imageUrl": "https://images.pexels.com/photos/870711/pexels-photo-870711.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260",
    "description": "Rivers and various other natural things ",
    "amount": "4562",
    "Id": "1234",
    "quantity": 1
  }
]

When i try to add the same object by clicking on the add to cart function then instead of if block to execute else get executed.
Below is the UI of the page upon which i am clicking on the add to cart button :- Ui image

below is the CartData.json output when i click on 3-4 times on the right pic of the given image :-

[
  {
    "title": "camera",
    "imageUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/Image_created_with_a_mobile_phone.png/1280px-Image_created_with_a_mobile_phone.png",
    "description": "girl clicking picture",
    "amount": "1254",
    "Id": "12345",
    "quantity": 1
  },
  {
    "title": "Mountain Picture",
    "imageUrl": "https://images.pexels.com/photos/870711/pexels-photo-870711.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260",
    "description": "Rivers and various other natural things ",
    "amount": "4562",
    "Id": "1234",
    "quantity": 3
  },
  {
    "title": "Mountain Picture",
    "imageUrl": "https://images.pexels.com/photos/870711/pexels-photo-870711.jpeg?auto=compress&cs=tinysrgb&dpr=3&h=750&w=1260",
    "description": "Rivers and various other natural things ",
    "amount": "4562",
    "Id": "1234",
    "quantity": 1
  }
]

And this is the UI i get :-

Ui image after clicking 3-4 times the Add to cart button

Below is the terminal image :-

terminal image

Could some one tell me why this is happening and how to solve this ???
Any help will be appreciated!



Solution 1:[1]

In cartList.forEach((product) => { you iterate over multiple objects. And for each iteration you take one execution path. If you want to debug it further you can add the product to the console.log

cartList.forEach((product) => {
    prodId = prodId.replace(/\s+/g, " ").trim();
    if (product.Id === prodId) {
        console.log("Product already exists", product); // added product to the log
        product.quantity += 1;
    } 
    else 
    {
        console.log("new product", product); // added product to log
        productList.forEach((element) => {
        prodId = prodId.replace(/\s+/g, " ").trim();
        if (element.Id === prodId) {
            element.quantity = 1;
            cartList.push(element);
        }
        });
    }
    // res.render("./shop/product-detail.ejs", { title: "Product Details", product, });
});

then you will see that execution of a if branch happens on an distinct iteration as the execution of the else branch.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1