“Load” function not setting variable Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of “Load” function not setting variable without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have two functions that save variables to LocalStorage. The first one saves a variable, “money”, but the second doesn’t. The global variable “money” does not get assigned.

function saveVars() {
    localStorage.setItem('money', money);
}

function loadVars() {
    var money = localStorage.getItem('money');
}

Answer

From your example, I can assume two alternatives :

1) you want to “load” the value into a global variable named “money” ? Your code doesn’t work because you declare a local variable “money” that only exists within the function loadVars. Don’t declare your variable (i.e. do not add the keyword var or any equivalent in the function). The assignment money = … will assign to the global variable “money” only if there is no other variable named “money” in a more specific scope — and it will do so even if the global variable was not declared.

function loadVars() {
    money = localStorage.getItem('money');
}

2) you want loadVars to return the value of the stored variable ? and then you can assign that to a global:

function loadVars() {
    return localStorage.getItem('money');
}

var money = loadVars();
We are here to answer your question about “Load” function not setting variable - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji