Search code examples
javascripthtmlglobal-variableslocal-variables

The function is not running well while using a global variable


I am trying to make a probability finder to take some random numbers and find the probability of a number from the array of random numbers. I have the following code :

/*********************Select Random Number**********************/

//Number of cases
var nOC = document.getElementById("noc").value;

function rollDice() {

  //Number of trials
  let nOT = document.getElementById("not").value;

  //Empty Array to be filled
  let array = [];

  //Loop which pushes random numbers in the empty array
  for (let i = 1; i <= nOT; i++) {
    array.push(Math.ceil(Math.random() * nOC));
  }

  //Display results in a paragraph
  document.getElementById("para").innerHTML = "Your random numbers are " + array;
}

/*********************Get Probability**************************/

function getProbabilityOf() {

  //Probability of...
  let oP = document.getElementById("op").value;

  //Check if the number is out of range. If no, then find the probability of given number
  if (oP >= noC) {
    alert("This number is out of the range of possible outcomes that you have selected in step 1");
  } else {
    //Some code here
  }
}
<!---------------------------Intro------------------------------>
<h1>Probability Finder</h1>
<hr/>
<p>With our probability finder, you can easily choose the number of possible cases and select the number of times you want to select a random case each time from the total cases and finally find the empirical probability of and case you want from the selected
  total number of cases.</p>

<!---------------------------Step 1------------------------------>
<h3><span class="bold">Step 1 :</span>Select total number of cases:</h3>

<select id="noc">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
</select>

<!---------------------------Step 2---------------------------->
<h3><span class="bold">Step 2 :</span>Select total number of trials</h3>

<select id="not">
  <option value="10">10</option>
  <option value="20">20</option>
  <option value="30">30</option>
  <option value="40">40</option>
  <option value="50">50</option>
  <option value="60">60</option>
  <option value="70">70</option>
  <option value="80">80</option>
  <option value="90">90</option>
  <option value="100">100</option>
</select>

<!----------------------------Step 3----------------------------->
<h3><span class="bold">Step 3 :</span>Get random numbers by experiment</h3>

<button onclick="rollDice()">Get random numbers</button>

<p id="para"></p>
<!----------------------------Step 4----------------------------->


<h3><span class="bold">Step 4 :</span>Get probability of a particular number</h3>


<select id="op" onchange="getProbabilityOf()">
  <option value="1">1</option>
  <option value="2">2</option>
  <option value="3">3</option>
  <option value="4">4</option>
  <option value="5">5</option>
  <option value="6">6</option>
  <option value="7">7</option>
  <option value="8">8</option>
  <option value="9">9</option>
  <option value="10">10</option>
</select>

Before declaring the second function, nOC was declared local to function rollDice. But after I declared the next function, I needed to access it to complete step 4 (as mentioned in the code snippet). So I removed the variable nOC from the function and declared it globally(as shown in the code snippet). The problem is that after declaring the variable as a global variable, none of the function was able to access it. To resolve this problem, I rechecked the syntax many times but found no problems with it (as per my knowledge). I tried changing the type of the variable from let to var and const but still, the problem was not solved. What could be the problem? As a new newbie in the field of coding, I know that small mistakes are made by me, but it is very important for me to know my mistakes and fix them.


Solution

  • It's generally not a good idea to use inline event handlers.

    The error stems from the inline handlers. onchange="getProbabilityOf()" executes when the document renders. So after the page is loaded the onchange attribute will have the value of whatever result getProbabilityOf() returned. That won't be a javascript function I suspect.

    Here are a few modifications to your code, making it work (technically). I have not checked if it's the right output, it's just some technical adjustments. Now you can use that as a base to continue your efforts.

    About event delegation...

    Not related to the code, but to 'number of cases' and for fun: What's a sample of size one worth?

    // store a reference to #noc
    const nOC = document.querySelector("#noc");
    
    // add event handlers (event delegation)
    document.addEventListener("click", rollDice)
    document.addEventListener("change",
      evt => {
        if (evt.target.id === "op") {
          return getProbabilityOf();
        }
      });
    
    
    function rollDice(evt) {
      if (evt.target.tagName !== "BUTTON") { return; }
      
      //Number of trials
      const nOT = +document.querySelector("#not").value;
      const nocValue = +nOC.value;
      //                    ^ retrieve #nOC value here
      //Empty Array to be filled
      let array = [];
    
      //Loop which pushes random numbers in the empty array
      for (let i = 1; i <= nOT; i += 1) {
        array.push( Math.ceil(Math.random() * nocValue));
        
      }
      //Display results in a paragraph
      document.querySelector("#para").innerHTML = `Your random numbers are ${array}`;
    }
    
    
    /*********************Get Probability**************************/
    function getProbabilityOf() {
      //Probability of...
      const oP = +document.querySelector("#op").value;
    
      //Check if the number is out of range. If no, then find the probability of given number
      if (oP >= +nOC.value) {
      //        ^ determine #nOC value here
        alert("This number is out of the range of possible outcomes that you have selected in step 1");
      } else {
        //Some code here
      }
    }
    <!---------------------------Intro------------------------------>
    <h1>Probability Finder</h1>
    <hr/>
    
    
    <p>With our probability finder, you can easily choose the number of possible cases and select the number of times you want to select a random case each time from the total cases and finally find the empirical probability of and case you want from the selected
      total number of cases.</p>
    
    <!---------------------------Step 1------------------------------>
    <h3><span class="bold">Step 1 :</span>Select total number of cases:</h3>
    <select id="noc">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
      <option value="5">5</option>
      <option value="6">6</option>
      <option value="7">7</option>
      <option value="8">8</option>
      <option value="9">9</option>
      <option value="10">10</option>
    </select>
    
    <!---------------------------Step 2---------------------------->
    <h3><span class="bold">Step 2 :</span>Select total number of trials</h3>
    
    <select id="not">
      <option value="10">10</option>
      <option value="20">20</option>
      <option value="30">30</option>
      <option value="40">40</option>
      <option value="50">50</option>
      <option value="60">60</option>
      <option value="70">70</option>
      <option value="80">80</option>
      <option value="90">90</option>
      <option value="100">100</option>
    </select>
    
    <!----------------------------Step 3----------------------------->
    <h3><span class="bold">Step 3 :</span>Get random numbers by experiment</h3>
    
    <button>Get random numbers</button>
    
    <p id="para"></p>
    
    <!----------------------------Step 4----------------------------->
    <h3><span class="bold">Step 4 :</span>Get probability of a particular number</h3>
    
    <select id="op">
      <option value="1">1</option>
      <option value="2">2</option>
      <option value="3">3</option>
      <option value="4">4</option>
      <option value="5">5</option>
      <option value="6">6</option>
      <option value="7">7</option>
      <option value="8">8</option>
      <option value="9">9</option>
      <option value="10">10</option>
    </select>