Why is the else block being executed even though the condition in the if block is true in Javascript?

While delving into Node.js, I encountered an issue with my cartData.json file not updating properly. Here's the code snippet in question:

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);
            }
          });
        }
      });
    }
    fs.writeFile(cartListDatapath_dir, JSON.stringify(cartList), (err) => {
      console.log(err);
    });
  });
  res.redirect("/cart");
});
module.exports = routes;

Here is the JSON data in the cart list:

[
  {
    "title": "camera",
    "imageUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/I...",
    "description": "girl clicking picture",
    "amount": "1254",
    "Id": "12345",
    "quantity": 1
  },
  {
    "title": "Mountain Picture",
    ...
]

When attempting to add the same object to the cart, the "else" block executes instead of the "if" block. Refer to the UI image below:

https://i.sstatic.net/88ors.png

Upon clicking multiple times on the image, the data in CartData.json appears as follows:

[
  {
    "title": "camera",
    "imageUrl": "https://upload.wikimedia.org/wikipedia/commons/thumb/b/b6/I...",
    ...
]

Related UI image can be found here:

https://i.sstatic.net/CaOSG.png

Additionally, a screenshot of the terminal is provided:

https://i.sstatic.net/jlUmZ.png

If anyone could shed light on why this issue is occurring and offer solutions, it would be greatly appreciated!

Answer №1

When you use

cartList.forEach((product) => {
you are looping through multiple objects, taking one execution path for each iteration. To delve deeper into debugging, consider adding 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); // product added to log
        product.quantity += 1;
    } 
    else 
    {
        console.log("new product", product); // product added 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, });
});

Observe how the execution follows a distinct path for the if branch compared to the else branch on each iteration.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Why is it that this JavaScript isn't working as intended in the popup form?

</br> s_foot"> * use ajax.jquery as control event. like $("#save").click(function(){.....}); <script type="text/javascript>" var wp; var position; var pid; var product_name; var production_date; In this script, I am attempting to re ...

React hook issue: useEffect not updating socket.io-client

Although I am attempting to receive updated values of react hooks inside the socket on function, unfortunately, it seems that the values are not being updated. Even if I edit the react hook values, the changes are not being reflected inside the socket. Her ...

A guide on using .map() with meta tags in Next.js

My goal is to map the content of meta, but currently my code is replicating multiple instances of the entire meta tags. Here is the code I have: {general.head.articleAuthor.en.map(( ) => ( <meta property="article:author" content={general.h ...

Can user-generated code execute Javascript Promises in its entirety?

Can one fully implement the JavaScript Promise class using only userspace code, without relying on any support from native code (such as the internals of JavaScript) that would typically only be accessible to those working on a JavaScript engine like the V ...

Bcrypt.compare failing to match the passwords

I implemented a bcrypt.compare function in my code, but I'm running into an issue where it seems to not be comparing the passwords correctly. Regardless of the input password, the function always returns a status of ok. Can someone take a look at the ...

Issue with socket malfunctioning when integrated with express

I’m encountering an issue with the socket in my program. While I can easily broadcast from any part of the program using "io" connection, I face limitations when trying to use "socket" for broadcasting unless it is within the same connection as "io." I a ...

Issue with padding in Material UI button component not being applied as expected

I am struggling with applying padding and styles to my Material UI component. Take a look at the code snippet below: import "./css/Landing.css"; import { Button } from "@mui/material"; function Landing() { return ( <div class ...

What are some ways to style an image that has been added using JavaScript using CSS?

I utilized a JavaScript function to add an image, which looked like this: function show_image(src) { var img = document.createElement("img"); img.src= src; document.body.appendChild(img); } But when I attempt to change its style using CSS: img ...

Change the default direction of content scrolling in CSS and JavaScript to scroll upwards instead of

I am currently working on a website where the navigation bar spans the entire width and remains fixed in place. Below the navigation bar is a cover image, followed by the main content section. As you scroll down, the navigation bar covers the image from t ...

"Return to previous view with the zoom back feature in CanvasJS

How can I implement a zoom back button in CanvasJS using jQuery or normal JavaScript? I've been attempting to place it near the ones in the top right corner, but something seems to be amiss. Alternatively, is it feasible to enable zooming in and out ...

Insert HTML content into an iframe with a callback function

We are receiving information from the backend server and need to transfer it to an iframe. In order to accurately set the height of the iframe to match the content, we must wait for the content to be loaded into the iframe. However, this process may not ha ...

Is there a live password verification tool available?

Currently, I am conducting some initial research for my school's IT department as a student employee. The students at our institution are required to change their passwords every six months, but many of them struggle with the various password regulati ...

Clear a variable that was sent through the post method in an ajax call

Within my JavaScript file, I have the following Ajax code: // Default settings for Ajax requests $.ajaxSetup({ type: 'POST', url: path + '/relay.php' + '?curr=' + currency + "&ver=" + Ma ...

Unable to generate a JSON string from the JavaScript object

I need help converting the object I receive from the server into a JSON file for use in a d3.js chart: data = { "dog ":"5", "cat ":"4", "fish ":"12", } The desired output is: { "name" : "animal", "children" : [ {"name":"dog" ...

Add rows to the table dynamically and then execute the script

My table dynamically creates rows when a button is clicked, and there is an input box with an auto suggest script. The auto complete works fine on the default first box, but not on the dynamically added row. How can I make the auto complete script work o ...

Passing data between multiple components in Vue.js and Laravel: Best practices

require('./bootstrap'); window.Vue = require('vue'); Vue.component('exampleComponent1', require('./components/exampleComponent1.vue')); Vue.component('exampleComponent2', require('./components/exampl ...

Convert inline javascript into an external function and update the reference to `this`

I'm currently in the process of converting some inline JavaScript code triggered by a button's onclick event to a regular JavaScript function. In my previous implementation, I successfully used the "this" reference to remove a table column. Howe ...

Is there a way to extract the text from the inner div of an element using nightwatch.js?

I'm attempting to retrieve the content of a cell within a table, with the following CSS structure: <div data-testid="cellvalue_row-1_col-0" class="Table-cellContent" xpath="1"><span data-testid="tableCellCon ...

JavaScript Auto-Closing Modal Pop-Up in HTML

I am looking to implement a feature similar to what is seen on Banks or American Express websites, where a MODAL Popup notifies users that their session is about to expire. In addition to this, I would like to include an "Auto-Close" Popup event that will ...

Using both Ajax and a standard submit can be applied to a single form in jQuery

I need to implement a confirm step on one of my pages. Here's what I want to achieve: When the user clicks 'submit', an AJAX request is triggered, which performs the necessary action and then displays a confirmation dialog If the user ...