'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.
Solution 1:[1]
You can't over declare the var's
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 + " $";
}
}
<button onclick="plusOne()">Plus five cents</button>
<p id="amount">0 ¢</p>
Solution 2:[2]
At the beginning try don't declare variables using var. Use 'const' when you know value and this value is constans otherwise use 'let'.
let dollar = 0;
let cents = 0;
function plusOne() {
if (cents < 95) {
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 =+ 0.05;
document.getElementById("amount").innerHTML = dollar + " $";
}
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Leandro William |
| Solution 2 | Gostii |
