2

I'm having problems creating a global variable and resetting it through jquery. here is my code

var x = 1;
$(document).ready(function () {
    $("#button").click(function () {
        if(x === 1) {
            alert("test1");
            var x = 2;
        } else if(x === 2) {
            alert("test2");
            var x = 3;
        } else {
            alert("test 3");
        }
    });
});

I want to be able to click the same button three times and have all the tests appear, but instead it goes straight to the last option "test 3". I apologize if this is a silly question, but I'm a bit new to jquery and javascript.

1 Answer 1

3

Just remove the var from the variable assignment inside the click event callback. The var makes the variable local to that scope/closure.

 if (x === 1) {
      alert("test1");
      x = 2;
  }
  else if (x === 2) {
      alert("test2");
      x = 3;
  }
  else {
      alert("test 3");
  }

As a side point the very first var is not necessary, var x = 1 and x = 1 does the same thing when the code is not in a closure/function. All they are doing is assigning window.x = 1.

Sign up to request clarification or add additional context in comments.

5 Comments

"closure" is not a synonym for (anonymous) functions in javascript. If you wanted to say "anonymous function" then you needed to say "anonymous function". "closure" term in your expression makes not much sense.
That is true, but functions do create a closures.
"That is true, but a function does create a closure" -- this doesn't make much sense either. developer.mozilla.org/en-US/docs/JavaScript/Guide/Closures "A closure is a special kind of object that combines two things: a function, and the environment in which that function was created"
Just to be more clear: as you pointed out - var defines a variable local to the current scope. That's it. closures are irrelevant here, because the main closure feature is that it handles variables from the outer scope, while we are talking about local scope.
thanks so much for the help, your explanation was clean and clear!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.