Global Variables and the .click Function

I’m using jQuery. Can someone please explain why I cannot modify the global variable x within the ,click function below? After clicking on a link, the value of x is still an empty string, not “test”. I’ve noticed that this occurs with .click functions. I’m trying to understand why and how I can fix it without just putting the console.log(x) inside my click function. I specifically want to know how a global variable can be modified within the click function. I tried to make the example easy to understand and it’s just a generic example to communicate my issue.

var x = " ";

    $('a').click(function() {
        x = "test";
    });

    console.log(x);

Thanks guys!

var x = " ";

$('a').click(function() {
    x = "test";
    console.log(x);
});

Try it this way and see if it works as you’re expecting.

The reason is because the console.log(x) is only executed once at page load before you can click the button. The code doesn’t all re-evaluate when you trigger .click(), only the code in the callback function()

1 Like