Reputation: 15
I am making a javascript based life game, and I am trying to make a balance system for it. When I click on my button that calls my function balance(), an error occurs where the console fails to find my defined variable. Please help here is my code:
var balance;
function balance() {
let newbalance = balance + 100;
let balance = newbalance;
document.getElementById("balance").innerHTML = (balance);
}
<link href="https://fonts.googleapis.com/css?family=Mukta+Malar" rel="stylesheet">
<center>
<h1 class="title">Life Game</h1>
</center>
<table>
<tr>
<td class="mainTd">
<h1 id="balance">0</h1>
</td>
<td class="mainTd">
<h1 id="state">Begger</h1>
</td>
</tr>
</table>
<button onclick="balance()">Click Me</button>
Upvotes: 0
Views: 86
Reputation: 204
there are three issues.
if you had not other issues, the code would still not work. you create a variable balance
without setting the variable thus it will be undefined
. Thus adding 100 to it will result in a NaN
> var balance
undefined
> balance + 100
NaN
At first you define a global uninitialised variable balance
for storing the balance value. Then you define function balance
which will be assigned to the same variable. Thus the variable balance
will point to a function from now on.
> var balance;
undefined
> balance
undefined
> function balance() {}
undefined
> balance
[Function: balance]
Inside a the function you define a block scoped(let
) variable balance
. This will be a completely new variable that exists only inside of the function, thus anything you do to it would not affect the balance
variable outside of the function. This is called shadowing and linters should warn about this.
> var balance = 11;
undefined
> function calc() {
... let balance = 22;
... return balance;
... }
undefined
> balance
11
> calc()
22
> balance
11 <- original balance is still the same
var balance = 0; // set initial value
function calculateBalance() { // use unique name for function
let newbalance = balance + 100;
balance = newbalance; // use the global variable instead of defining a new one
document.getElementById("balance").innerHTML = (balance);
}
<link href="https://fonts.googleapis.com/css?family=Mukta+Malar" rel="stylesheet">
<center>
<h1 class="title">Life Game</h1>
</center>
<table>
<tr>
<td class="mainTd">
<h1 id="balance">0</h1>
</td>
<td class="mainTd">
<h1 id="state">Begger</h1>
</td>
</tr>
</table>
<button onclick="calculateBalance()">Click Me</button>
Upvotes: 0
Reputation: 6904
you have named your function balance
which is shadowing the variable outside.
after changing the name of function give some default value to balance ,
var balance = 0;
Upvotes: 2