1

This may sound a newbie question but I'm having really hard time with variable scopes in Javascript.

I have the following JS snippet:

<script>
window.IDFVPlugin.getIdentifier(function(result){ uuid = result; });
alert(uuid);
</script>

I want to use the variable uuid anywhere in the script outside the window object. uuid returns the correct value only when inside the object and the value is lost when outside. So the alert above will log an undefined variable error.

Michael Samuel
  • 3,820
  • 12
  • 45
  • 85

1 Answers1

7

You use a callback function. Result should be used inside of callback body. If you try to use it immediately after main function call - it will not be yet available

window.IDFVPlugin.getIdentifier(function(result){
 uuid = result;
 alert(uuid); 
});
Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136
  • 1
    That's right. I've created this [jsfiddle](http://jsfiddle.net/awolf2904/goq91eg1/) to show an asynch callback. If it would be a synchronous callback the approach with adding the result to the window obj. or to a previous defined variable would work. For testing synch just uncomment `callback(data);` – AWolf May 16 '15 at 23:57