Changing a global variable from inside a function

Here I have a bit of a problem with this very simple Ive script written. The purpose of this script is to simply reduce the set number by each time the button is clicked. I can't do it .. My global variable being Number = 100 does not seem to change or change more than once. Sorry for not being able to explain this well. Here is the part I'm working on ..:

<script> var Number = 100; // Number i want changed and to keep changing each button click function outcome() { // Button calls this function Number = Number - 1; // Tries to change Global Number.. :/ } document.write(Number); // Has the Number written in the document </script> 
+4
source share
2 answers

Yes, conceptually this is correct. Only you do not call the function, at least not before writing Number to the document.

Btw, Number is a global reference to the Number constructor, so you should use a different variable name, lowercase at best.

 var num = 100; function outcome() { num--; } outcome(); document.write(num); // 99 

or

 <script> var num = 100; function outcome() { num--; alert(num); } </script> <button onclick="outcome()">Decrease!</button> 

( Demo on jsfiddle.net )

+7
source

You must call your function:

 <script> var Number=100 function outcome(){ Number=Number-1 } outcome(); // call the function here document.write(Number) </script> 

or not use the function in the first place:

 <script> var Number=100 Number=Number-1 document.write(Number) </script> 
+2
source

All Articles