4

Here im having a bit of an issue with this very simple script Ive written up. The aim for this script is to simply reduce the given number by one each time the button is clicked. I cannot appear to do this.. My global variable being the Number=100 doesnt appear to change, or change more than once.. Apologies for not being able to explain this well. Here is the part im 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> 
Lipis
  • 21,388
  • 20
  • 94
  • 121
Darryl Chapman
  • 379
  • 2
  • 8
  • 22

2 Answers2

7

Yes, conceptually this is right. Only you are not calling the function, at least not before writing Number to the document.

Btw, Number is the global reference to the Number constructor so you should use another 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 at jsfiddle.net)

Bergi
  • 630,263
  • 148
  • 957
  • 1,375
  • The global `Number` is writeable. – the system Mar 24 '13 at 21:28
  • @thesystem: Is it? Oh, it really is. Fixed now. – Bergi Mar 24 '13 at 21:30
  • 2
    One would think it wouldn't be, but then one would forget that we're talking about JavaScript. ;-) – the system Mar 24 '13 at 21:30
  • @DarrylChapman: Then you shouldn't be using `document.write()`. That's meant to be used as the page is loading... not after it's already loaded. – the system Mar 24 '13 at 21:34
  • I am calling my function from the use of a button. I have tweaked the code a bit with using num as the variable and such, but it is changing the variable once, its alerting me 99, and if i click the button again, its coming up with 99 again. – Darryl Chapman Mar 24 '13 at 21:36
  • This coding has been fixed, apologies as i had realised my mistake lied within my button line being within form tags which were in the body. After moving it to my head tags, it works and functions and as it should! Thank you guys, much appreciated! – Darryl Chapman Mar 24 '13 at 21:40
2

You have to call your function:

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

or don't use a function in the first place:

<script>
var Number=100    
Number=Number-1   
document.write(Number) 
</script> 
Horen
  • 11,184
  • 11
  • 71
  • 113