Shared variable in Javascript

Dear all,

May i know how to create variable in Javascript that can be shared by two button’s onClick function ?

For example:
Button1 and button2 is calling increaseXValue()
The increaseXValue() function will increase the variable x count by 1 every time button1 or button2 is clicked.
After button1 clicked, x variable value will be increased by 1. Then after button2 clicked, x variable will be increased by 1 again. So the total value of x variable is 2.
And this variable X value need to be available to other function in Javascript as well.

Thank you.


Any variable you declare outside of a function will be global and accessible in all functions:

var x=0;

function increaseXValue() {

function someOtherFunction() {
  alert("x=" + x);

<input type="button" value="Button 1" onclick="increaseXValue()">
<input type="button" value="Button 2" onclick="increaseXValue()">

You can just declare the variable count outside of any function with var

var count = 0;

That’s it.
But this is not a good style. Normally you try to avoid global variables. For example you can write your code in a class and store count as a class variable.

class myClass
    count = 0;

        …. Put your addEventListener code here and use this.count instead of count only….

If you find no way to avoid a global variable you should put it in your own namespace to avoid duplicates which will drive you crazy finding an error if in some other code count is also declared.
For this you can create a namespace in the window

window.myname = {};

And then use this namespace for your global variables

window.myname.count = 0;

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.