Reputation: 4306
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.
Upvotes: 1
Views: 2349
Reputation: 1
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>
Upvotes: 0
Reputation: 21666
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:
Upvotes: 2
Reputation: 6096
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 s
s refer to the same variable.
I'd recommend researching "scope in Javascript" and learning more about how "var" and variable scope work.
Upvotes: 2