Change the value of a var from a function to another

2804 views javascript
1

I am making a javascript based life game, and I am currently working on the Job change. If you become a cleaner, for example, you get 5 dollars instead of one. I can't figure it out. So when the player gets the job cleaner the money is still 1$ every second instead of 5$ Here is my code:

var balance = 0;
var clotheL = 0;
let amt = 1;
setInterval(() => balanceSys(1), 1000);

function balanceSys(){
    let changeBal = document.getElementById("balance");
    let newbalance = balance + amt;
    balance = newbalance;
    changeBal.innerHTML = ("$" + balance);
}

function tJ(){
    if(balance > 19) {
        clotheL = 2;
        newbalance = balance - 20;
        balance = newbalance;
        alert("Bought T-Shirt and Jeans")  
        document.getElementById("clothes").innerHTML = ("T-Shirt & Jeans");
    }else{
        alert("Can't afford it.")
    }
}

function cleaner(){
    if(clotheL == 2){
        let amt = 5;
        document.getElementById("state").innerHTML = ("Cleaner");
    }
}

answered question

and what is not working in that code snippet? edit your question.

Done, it should be edited.

They're called function parameters for a reason. You should consider making amt a parameter of balanceSys().

1 Answer

4

In the cleaner function, you redefine the amt variable, rather than overwriting it

function cleaner(){
    if(clotheL == 2){
        let amt = 5;
        document.getElementById("state").innerHTML = ("Cleaner");
    }
}

becomes

function cleaner(){
    if(clotheL == 2){
        amt = 5;
        document.getElementById("state").innerHTML = ("Cleaner");
    }
}

posted this

Have an answer?

JD

Please login first before posting an answer.