Search code examples
javascriptglobalvar

How can I change global variables in javascript?


My html page displays a button that calls a function when it is clicked. I checked to make sure that the button works properly by displaying a message when clicked and it worked. I created this function to change the global varible but when I click another button on my html page to show the value of the varibles the varibles have not changed to the value I set them using my function. Could someone find the problem in my code below?

    var a = 5;
    var b = 16;
    var c = 27;

    function reset(){
    a = 0;
    b = 0;
    c = 0;
    }

My html code to call the function:

   <!DOCTYPE HTML>

   <html>
   <center>
   <script type="text/javascript" src="game.js" > </script>
   <form>
   <input type="button" value="Reset Variables" style="width:250px;height:50px" onclick="reset()" >
   </form>
   </html>

Javascript code to show the variables:

    function display(){

    document.write("A is equal to " + a + "<br/>");
    document.write("B is equal to " + b + "<br/>");
    document.write("C is equal to " + c );

}

Html to display the variables

   <!DOCTYPE HTML>

   <html>
   <center>
   <script type="text/javascript" src="game.js" > </script>
   <form>
   <input type="button" value="Show Variables" style="width:250px;height:50px" onclick="display()" >
   </form>
   </html>

Solution

  • change the function name to reset_vars or anything else. reset() is in-built DOM function used for resetting forms.

    http://www.w3schools.com/jsref/met_form_reset.asp

    There won't be any conflict when a global variable is used inside a function unless a local variable is defined. in such case, use window.variable_name to access global variable.