Home > Software engineering >  How do I add two variables intended to regularly update and get an up-to-date answer?
How do I add two variables intended to regularly update and get an up-to-date answer?

Time:01-20

I'm trying to add two variables together. Both variables are intended to change regularly. No matter how they change, though, the third variable that's meant to be the two of them added together has either no value if the two aren't declared at the start, or remains as the sum of the starting values.

I put together a little demo thing to test it, with buttons that adapt the "prodScore" variable, and a button intended to update the "score" value to the sum of invisScore and prodScore.

    <p>invisScore:<span id="invisScore"></span></p>
    <p>prodScore:<span id="prodScore"></span></p>   
    <p>invisScore   prodScore:<span id="score"></span></p>
    <p><button onclick="addProdScore()">Add 1 Production Score</button></p>
    <p><button onclick="minusProdScore()">Minus 1 Production Score</button></p>
    <p><button onclick="updateScore()">Update Score</button></p>
  
    <script>
    let invisScore = 5
    let prodScore = 0
        addProdScore = function(){
            prodScore  = 1
        document.getElementById('prodScore').textContent = prodScore;
        }
        minusProdScore = function(){
            prodScore -= 1
        document.getElementById('prodScore').textContent = prodScore;
        }
        updateScore = function(){
            document.getElementById('score').textContent = score;
        }
        var score = invisScore =prodScore
    </script>

This just gives me 5 every time, being the sum of the 0 value prodScore and the 5 value invisScore. What do I need to do to make the sum, "score" value be up to date?

CodePudding user response:

The score variable is set once when the page loads and then never updated. You could update it when updating the values which calculate it, for example:

addProdScore = function(){
  prodScore  = 1;
  score = invisScore =prodScore;
  document.getElementById('prodScore').textContent = prodScore;
}

Or perhaps make its calculation a function to be re-invoked when re-displaying the value:

updateScore = function(){
  document.getElementById('score').textContent = score();
}
var score = function() {
  return invisScore =prodScore;
}

Basically, any way you look at it, if you want the "score" to be updated then you need to re-calculate it with the new values.


As an aside, I'm not sure this does exactly what you intend:

score = invisScore =prodScore;

Are you also modifying invisScore here? For clarity you'd probably want to separate these operations into their own lines of code. As it stands, this line is confusing, and confusing code leads to bugs.

  • Related