user2217303
user2217303

Reputation: 356

How to declare and set a variable in jquery?

I have a basics question. In Jquery if I declare a variable and assign a value for it inside a function, how can I maintain this change? I thought it would overwrite it. Please Help.

This is a simple example of what I mean. The alert box shows 2 but how can I save 3 in x??

<script>
var x=2
$(document).ready(function(){
    (function(){
        x=3;
    });
    alert(x);
});
</script>

Upvotes: 1

Views: 2532

Answers (3)

Nachshon Schwartz
Nachshon Schwartz

Reputation: 15795

The function you wrote is not used. Try this instead

<script>
    var x=2
    $(document).ready(function(){
        (function(){
            x=3;
        })();
       alert(x);
    });
</script>

Notice the added parenthesis which invoke the function immediatly after declaration.

A working jsfiddle: http://jsfiddle.net/nayish/x9kzefc2/

In your example since x is defined outside of the function it is entered into the functions closure and so , if you would have immediatly, or some time later on run the function it would have changed the value of x that was defined outside the functions scope.

Explanation on self invoking functions:

https://sarfraznawaz.wordpress.com/2012/01/26/javascript-self-invoking-functions/

Upvotes: 1

Giedrius
Giedrius

Reputation: 94

You create a function, but not set and don't call.

See here, how to set and call it:

var x=2
$(document).ready(function(){
    var test = (function(){
        x=3;
    });
    test();
    alert(x);
});

or

var x=2
$(document).ready(function(){
    (function(){
        x=3;
    })();
    alert(x);
});

Upvotes: 0

Barmar
Barmar

Reputation: 782785

You're written a function expression, but it's not part of an IIFE, so it's not getting executed. You have to put () after the function expression to execute it:

var x = 2;
$(document).ready(function() {
  (function() {
    x = 3;
  })();
  alert(x);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Upvotes: 2

Related Questions