0

consider function ‍seletcolor() below:

function seletcolor() {
    var button = document.querySelector("button");
    var a = 1;
    button.onclick = function (e) {
        a = a++;
    };
    console.log(a);
}

Once I click on button, I want to print out the value of the variable a inside the event outside the event.

Mojtaba Ahmadi
  • 1,044
  • 19
  • 38
CodeBoy
  • 11
  • 1
  • 3
    Possible duplicate of [What is the scope of variables in JavaScript?](https://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript) – Esko Sep 18 '18 at 12:24
  • 1
    why is that you are not adding console.log(a) inside the handler ? – trk Sep 18 '18 at 12:25

1 Answers1

0

Since you want to print the value when they click, you need to put the console.log call inside the onclick function.

function seletcolor() {
    var button = document.querySelector("button");
    var a = 1;
    button.onclick = function (e) {
        a++;
        console.log(a);
    };
}

Also, to increment a variable it's just a++. That performs the assignment, you don't need to assign it back (which actually undoes the increment, because a++ returns the old value).

Barmar
  • 741,623
  • 53
  • 500
  • 612