...but if I do it out, i get the previous value, because I am not modifying global locations variable...
Yes, it is, it's just doing it later. The call to geocode
is asynchronous, and so won't see the result until the callback is made. Code immediately after the geocode
function call will run before the callback runs, and so you won't see any change.
Let's use a simpler example for illustration:
// A variable we'll change
var x = 1;
// Do something asynchronous; we'll use `setTimeout` but `geocode` is asynchronous as well
setTimeout(function() {
// Change the value
x = 2;
console.log(Date.now() + ": x = " + x + " (in callback)");
}, 10);
console.log(Date.now() + ": x = " + x + " (immediately after setTimeout call)");
If you run that (fiddle), you'll see something like this:
1400063937865: x = 1 (immediately after setTimeout call) 1400063937915: x = 2 (in callback)
Note what happened first.