Reputation: 10926
I have created a variable and tried to set its value by a function. But this value in not accessible outside that function
<script type="text/javascript">
$(document).ready(function () {
var pId;
getProfiles(id,function(b)
{
pId=b;
alert(pId); // It works fine...
});
alert(pId); // undefined...
});
</script>
Upvotes: 2
Views: 2241
Reputation: 5546
When you assign to pId
new value without declaration variable pId declared in global scope. But you have a local pId
variable. So when you call alert inside callback it show value of GLOBAL pId
and you second alert show your LOCAL pId
value.
function f() { d = 2; };
function a() {
var d = 1;
f();
alert(d);
}
a();
alert(d);
First alert will show 1 and second will show 2. So second alert in you code will always show undefined
no matter when callback called.
Upvotes: 1
Reputation: 8166
You declare pId
but you don't assign any value to it, so by default is undefined
, the alert in the same scope is then evaluated, and prints 'undefined
'.
The anonymous function is a callback that is called by getProfiles()
(maybe asynchronously), and you cannot assume that it will be called before the outer alert
is called.
<script type="text/javascript">
$(document).ready(function () {
/* You declare it but you don't assign any value to it...
* so by default is undefined
*/
var pId;
getProfiles(id,function(b)
{
pId=b;
alert(pId); // This is called only once your anonymous callback is called...
});
alert(pId); // Alerts 'undefined'
});
</script>
Upvotes: 2
Reputation: 35679
The first alert works because it is just after the value is set by the callback function you're passing to getProfiles
.
The second alert in your code example still shows the value "undefined" because the callback function you are passing to getProfiles hasn't executed yet.
Also, just a side note: pId
is local to the function you are passing to jQuery's ready event, it is not a global variable.
Upvotes: 3