1

How can I update the variable value in jQuery? How can I update the variable value as it updates in functions? I checked the scope of variable in jQuery but I did not understand.

<script>
$(document).ready(function(){
  var s = 9;
  function data()
  {
     var s = 11;
  }
  data();
  alert(s);
});
</script>

I want 11 in alert for data but I am getting 9. how can I update the value if its updated in functions. please help me out for this.

Wagh
  • 4,202
  • 5
  • 39
  • 62
  • I think you mean "i want 11 in alert for data. but i am getting 9"? – GMA Dec 30 '14 at 11:32
  • 2
    remove the `var` from `s = 11`. But how you get 70 or 80 from that I have no idea – Rhumborl Dec 30 '14 at 11:32
  • possible duplicate of [how to change value of global variable inside of function](http://stackoverflow.com/questions/10872006/how-to-change-value-of-global-variable-inside-of-function) – waki Dec 30 '14 at 11:32
  • 1
    `var s = 11;` creates a *local* variable, which shadows global one. Remove `var` keyword to access global scope `s`. – dfsq Dec 30 '14 at 11:32

3 Answers3

2

I think you meant 11 not 80, or maybe you're not explaining it correctly.

Here s is global var, you can modify its value in data function. When you use var s in data function it creates a new variable names s whose scope is limited to that function only. That's why you get 9 outside its scope.

$(function(){
    var s = 9;
    function data()
    {
        s = 11; //removed var from here, if you use var here it will...
                //create new variable whose scope will end outside this function.
    }
    data();
    alert(s);
});

Recommend reading:

Chankey Pathak
  • 21,187
  • 12
  • 85
  • 133
2

First of all, this isn't a question about jQuery. The "$(document).ready"... wrapper in your code isn't relevant to the question.

Secondly, like I said in my comment, I'm assuming that the "70" and "80" in your question are mistakes and you meant to say "9" and "11".

To answer your question, you need to remove the var before s = 11. This code should do what you want:

var s = 9;

function data()
{
   s = 11;
}

data();
alert(s);

When you add "var", you're telling the code that s should only exist within the scope of the current function (data), and overrides any other variables called "s" in outer scopes. Without "var", the two ss refer to the same variable.

I'd recommend researching "scope in Javascript" and learning more about how "var" and variable scope work.

GMA
  • 5,816
  • 6
  • 51
  • 80
0

Hi i don't think that u can get 70 in alert from this script. and we can't get 80 in alert with these values, from this script u will get 9 in alert box, because u defined var s as two times, one is global and other one is private, when u are going to alert then script take the global. u can get 11 in alert box by using the following script:

<script>
$(document).ready(function(){
  var s = 9;
function data()
{
   s = 11;

}
data();
alert(s);
});
</script>