Search code examples
javascriptfunctionvariables

How to update a variable that depends on another variable in a function?


In the sample code below, note that the value of the variable dependent depends on the variable prereq. When the function changePrereq is called, it changes the value of prereq. This change is shown if logged, but it isn't reflected in the value of dependent. Instead, when dependent is put into a span, it shows Some text - undefined.

How can I have dependent change depending on the value of prereq?

P.S. Thanks everyone for the advice. For myself, I chose the answer from "ztcollazo" as the right decision.

"outis" - Thank you for your explanations. I will definitely pay attention to your recommendations and study them in more detail!

var display = document.getElementById('text'),
    prereq,
    message = "Some text - " + prereq;

function updateDisplay() {
    display.innerHTML = message;
    console.log(prereq);
}

function changePrereq() {
    prereq = "I am some text.";
    updateDisplay();
}
<p><span id="text"></span></p>
<button onclick="changePrereq()">Click</button>


Solution

  • The problem is that changeMyText doesn't update when someText does. You need to define changeMyText inside of the changeTextFunc function and then pass someText as a parameter.

    Example:

    var myText = document.getElementById('text');
    var someText1;
    
    var m1 = 1;
    
    function changeTextFunc(someText, m) {
      var changeMyText = "Some text - " + someText;
      if (m > 0) {
        myText.innerHTML = changeMyText;
      } else {
        console.log('m < 0');
      }
    }
    
    function changeText() {
      someText1 = "I a'm some text.";
      changeTextFunc(someText1, m1);
    }
    <div>
      <button onclick="changeText()">Click</button>
      <p id="text"></p>
    </div>