Steps to assign a localstorage variable within a function

Looking for a solution to this issue:

function sumFood (total, itemArray){
    var total = 0;
    for (var i=0; i<itemArray.length;i++) { 
        total += Number(itemArray[i]);
    }
    localStorage.setItem('total', total);
}

sumFood (GLC,GLCT); 
sumFood (LIP,LIPT);

I am experiencing an unexpected problem where the result in localStorage is showing as undefined, even though console.log shows the correct result. Any advice on how to resolve this?

Answer №1

You received an undefined value because the key was hardcoded in this line:

localStorage.setItem('tot',tot);

The key should change dynamically based on the parameters passed. Additionally, it is not recommended to name a variable inside a function the same as its parameter as it can lead to confusion. Consider using the following approach:

function sumFood (tot,tab_cout){
  var total = 0;
  for (var i=0; i<tab_cout.length;i++) {total += Number(tab_cout[i]);}
  localStorage.setItem(`${tot}`,total);
}

sumFood(GLC,GLCT); 
sumFood(LIP,LIPT);

This will store the sums in separate keys in localStorage. If you want to store all key-value pairs under one key, such as 'tot' in localStorage, then 'tot' needs to be an array of objects. Try the following modification:

function sumFood (tot,tab_cout){
  let total = 0;
  for (let i=0; i<tab_cout.length;i++) {
    total += Number(tab_cout[i])
  }
  const savedTot = JSON.parse(localStorage.getItem('tot')) || []
  const addedTot = savedTot.push({ [`${tot}`]: total })
  localStorage.setItem('tot', JSON.stringify(addedTot))
}

sumFood(GLC,GLCT)
sumFood(LIP,LIPT)

// if GLC and LIP are variables, otherwise you should put them in string. Like this:

sumFood('GLC',GLCT)
sumFood('LIP',LIPT)

To retrieve the values later on, use the following:

const getTot = JSON.parse(localStorage.getItem('tot')) || []
console.log(getTot) // you will see your expected output

Answer №2

In order to obtain the required result, I had to utilize the return statement for the total value without the need for storage. Therefore, it seems that your solution is accurate for the specified task.

 function sumFood (tot,tab_cout){
        var total = 0;
        for (var i=0; i<tab_cout.length;i++) { 
            total += Number(tab_cout[i]);
        }
    return total; 
     
    }
    
    sumFood (GLC,GLCT); 
    sumFood (LIP,LIPT);

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

exploring the contrast of css versus javascript selectors

Could you please explain the contrast between div#name and #name? Is there a significant difference when using class or id to position an element? Thank you for your help. ...

Is it possible to pass a JSON file as a JavaScript object in Express using Node.js?

When attempting to import a JSON file into my code using the line below, I am encountering an issue where the jsonConfig variable is being populated with a JavaScript object instead of the expected config file. This allows me to directly access jsonConfi ...

Ways to remove newly added tasks using JavaScript function?

I have an existing list of li elements in my HTML that can be deleted using JavaScript. However, whenever I add a new li, the delete function no longer works on the newly added item. I suspect the issue lies within the current implementation of the for loo ...

The error handler function is missing in Zepto's $.post method

When I was using Zepto instead of jQuery, I noticed that while the $.ajax method has an error handler, other methods like $.post and $.get do not. Do you know why this is the case? Function Signature $.post(url, [data], function(data, status, xhr){ ... }, ...

Having issues with Vue.js and the splice method not functioning properly on an array row

Having an Object array, I noticed that when I try to remove an object from the array list, only items are deleted from the end. <div class="hours" v-for="(time, index) in hour" :key="index"> So, I decided to place a cli ...

What is the best way to obscure a potential phone number within a string of text?

Utilizing Google Cloud DLP in node.js to censor phone numbers from a string, even if the string contains other words. Check out more information on how to use this feature here. For instance, I need to redact the phone number in the following sentence: Do ...

Set boundaries for the width and height of an image in the input field

Looking to restrict the size of an image in an input field using HTML, CSS, and JavaScript/jQuery. Goal is to maintain a perfect square aspect ratio for profile photo uploads (for example, 200x200 or 300x300). ...

Adjustment in orientation compared to the position of the head-mounted display

At the moment, I am utilizing a system where the camera in the world moves based on the change in position from the hmd. The problem arises when I turn to face the positive x-axis and move forward - only the x-axis changes, making it impossible to walk for ...

Issues with the functionality of the dropdown toggle menu in the Navbar when utilizing the Reactjs library alongside Bootstrap

After trying to implement a nav bar using code from the bootstrap library, I noticed that the dropdown menu is not functioning correctly. Here is the code snippet I used: <li class="nav-item dropdown"> <a class="nav-link dro ...

Encountering issues with basic login functionality using Node.js and MongoDB - receiving a "Cannot

I'm experiencing some difficulties trying to set up a login for my website. I have a user registered in my database with the email: [email protected] and password 123. The issue arises when I attempt to use the POST method, as it returns the fo ...

Issue: Unable to update reference: The primary argument includes an invalid key

Encountering a curious error on Firebase while working with Vue.js: The process goes smoothly the first time, and I can execute the following function multiple times without any issues. addSpace: function (newSpace) { let userId = firebaseApp.auth(). ...

"Vue's scope is always kept fresh and updated

Recently I've been working with a combination of vue.js and jquery. In my current scenario, I attempted to insert sidebar html code (containing vue syntax) into main.html using jquery. Unfortunately, upon injecting sidebar.html into main.html, vue.js ...

my AJAX code isn't redirecting me to the desired URL in the background

I am seeking to utilize ajax for navigating to a php script in the background in order to execute certain commands. However, I'm encountering an issue where the commands are not being executed. This leads me to believe that there may be an error in my ...

What strategies can be utilized to raise the max-height from the bottom to the top?

I am facing the following coding challenge: <div id = "parent"> <div id = "button"></div> </div> There is also a dynamically generated <div id="list"></div> I have successfully implem ...

Error in Rails 4: Unable to call $(...).previous function - TypeError

I've been attempting to create a link labeled "remove" underneath a text field to use JavaScript to destroy and hide it, but I'm running into an issue where it doesn't work and I'm receiving this error in the console: TypeError: $(...). ...

Inserting text directly into innerHTML instead of relying on innerText

Can we insert a string into innerHTML without relying on innerText? For example: var sentence="<b>hello there</b>"; document.querySelector(".container").innerHTML='<span class="thing"></span>'; document.querySelecto ...

Retrieve the current day's value from an array

I have a list of days with corresponding opening and closing hours, now I need to find the operating hours for today. For instance, if it's Friday, then the current hours should be "11:30 AM – 9:30 PM". How can I achieve this using JavaScript? ["Mo ...

The changing perspective in relation to the current position of a background

I am currently working on implementing a parallax effect, which is mostly successful. However, I have encountered a minor issue. Instead of the parallax effect being relative to the element's current position, it abruptly jumps to position 0. How can ...

What is the method for deleting an object that matches the req.params.id?

router.delete('/shopping-cart/:id', (req, res) => { let cart = new Cart(req.session.cart); console.log(req.params.id); console.log(cart.generateArray()); }); After running console.log(cart.generateArray()), the output is as follow ...

Error occurred due to an improperly formatted authorization header while attempting to upload an object to S3 using the JavaScript SDK

When attempting to upload an object to Amazon S3 using their JavaScript SDK, I encounter the following error message: <Error> <Code>AuthorizationHeaderMalformed</Code> <Message>The authorization header is malformed; the reg ...