Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to make a variable not used out of scope?

How can I make this variable not used out of scope. I keep getting this error in JSFiddle: 'variable' Used out of scope. I don’t know what that means or why it occurs. I tried to fix it myself and that just made it worse. I looked all over the internet and couldn’t find anything, so stack overflow was my last resort. Anyways, here is my code. Or, If you don’t prefer JSFiddle, here:

var dollar = 0;
var cents = 0;

function plusOne() {
  if (cents < 95) {
    var cents = cents + 5;
    document.getElementById("amount").innerHTML = cents + " ¢";
  } else if (cents == 95) {
    var dollar = 1;
    document.getElementById("amount").innerHTML = dollar + " $";
  } else if (cents == 100) {
    var cents = 0;
    var dollar = dollar + 0.05;
    document.getElementById("amount").innerHTML = dollar + " $";
  }
}
<button onclick="plusOne()">Plus five cents</button>
<p id="amount">0 ¢</p>

As you can see, it does not change the value at all. I don’t know what is going on with it.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

According to MDN (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var)

The var statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value.

The case here is that every time the function plusOne executes, you create a new variable with the name cents or dollar or both, whose scope is bind to the plusOne function.

A more optimal way to write your function, is instead of declaring a new variable, to change the value of your already existing variables.

e.g.

var dollar = 0;
var cents = 0;

function plusOne() {
  if (cents < 95) {
    cents = cents + 5;
    document.getElementById("amount").innerHTML = cents + " ¢";
  } else if (cents == 95) {
    dollar = 1;
    document.getElementById("amount").innerHTML = dollar + " $";
  } else if (cents == 100) {
    cents = 0;
    dollar = dollar + 0.05;
    document.getElementById("amount").innerHTML = dollar + " $";
  }
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading