Search code examples
javascriptjqueryjsonlocal-storageundefined

Variable read as undefined only in conditional statements


I have a jQuery function to remove items from a cart object that is stringified in local storage.

function removeItemFromCart(pid){
    console.log("removing: ", pid)
    let cart = JSON.parse(localStorage.getItem('cart'));
    
    $.each(cart, function(index, value){
        console.log(value.productId);
        var p_id = value.productId;
        console.log(p_id);
        if (p_id == pid){
            cart.splice(index, 1);
            return;
        }
    });

    localStorage.setItem('cart', JSON.stringify(cart));

}

However in my console I get the following error (for context my js file is cart.js):

Uncaught TypeError: Cannot read properties of undefined (reading 'productId')
at cart.js:77:30
at Function.each (jquery.min.js:2:3003)
at removeItemFromCart (cart.js:76:11)
at HTMLButtonElement.<anonymous> (cart.js:46:21)
at HTMLButtonElement.dispatch (jquery.min.js:2:43064)
at v.handle (jquery.min.js:2:41048)
(anonymous) @ cart.js:77
each @ jquery.min.js:2
removeItemFromCart @ cart.js:76
(anonymous) @ cart.js:46
dispatch @ jquery.min.js:2
v.handle @ jquery.min.js:2

and points to the p_id variable in the if-statement being undefined for some reason. Originally the if statement was (value.productId == pid) but I changed it to debug this very issue. I was testing things out and found that value.productId does exist in items in the cart in my local storage, that I am capable of saving it in a variable and even logging it without issue.

It is only when I try to use it in a conditional statement that it gets read as undefined but I have no clue as to why. Below is another function in the exact same file that essentially uses the exact same condition and it works fine without hiccups.

function updateCart(productId, quantity){
    let cart = JSON.parse(localStorage.getItem('cart'));
    let foundProduct = false;
    $.each(cart, function(index, value){
        if (value.productId == productId){
            value.quantity += quantity;

            if (value.quantity < 0){
                cart.splice(index, 1);
            }
            foundProduct = true;
            return;
        }
    });

Does anybody know why this issue occurs and how I would go about debugging it?

For reproducability my local storage has a key called cart and a value of [{"productId":2,"quantity":3},{"productId":6,"quantity":1},{"productId":5,"quantity":1}]


Solution

  • I had my analysis of the issue wrong.

    Having value.productId in my conditional statements was not the issue by itself. After some debugging I found it was the fact that I was doing cart.splice() whilst iterating over the cart which messes things up with the index numbers the program uses during the loop. This is why it complained about the value being undefined.

    The following stackoverflow post helped me identify my issue and presents various solutions to it, including iterating over the array in reverse: looping through an array whilst removing items