0

I'm trying to use a variable outside an anonymous function. Not declaring it as var in the function should make it's scope global but it doesnt work in this case. I think you have to call the function first but how do i call this function? PS: I'm just learning js. Thanks.

$(document).ready(function(){

    navigator.geolocation.getCurrentPosition(function(position) {
       x = position.coords.latitude;
       y = position.coords.longitude;
    });

console.log(x);}); //end of ready
Gurwinder Singh
  • 38,557
  • 6
  • 51
  • 76
gshaineala
  • 485
  • 1
  • 4
  • 8
  • 1
    I removed java tag – Gurwinder Singh Dec 31 '16 at 11:38
  • _Not declaring it as var in the function should make it's scope global_ - no it shouldn't. Use `window.x` to declare this var in global scope. – 31piy Dec 31 '16 at 11:40
  • 1
    @31piy: Actually, it does, in loose mode, if you assign to it as in the above. It creates an *implicit global*. See my blog post: [*The Horror of Implicit Globals*](http://blog.niftysnippets.org/2008/03/horror-of-implicit-globals.html) – T.J. Crowder Dec 31 '16 at 11:41
  • 1
    @T.J.Crowder Didn't know that. Thanks for pointing it out :) – 31piy Dec 31 '16 at 11:42
  • @T.J.Crowder Could you just explain why this is a duplicate of the question about async returns? Its not obvious that there is anything async here. – Vanquished Wombat Dec 31 '16 at 12:00
  • @VanquishedWombat: [`navigator.geolocation.getCurrentPosition`](https://developer.mozilla.org/en-US/docs/Web/API/Geolocation/getCurrentPosition) is an async operation, that's why it provides its information in a callback. Even if we didn't have docs for it, we could infer that, since If it weren't async it wouldn't make sense to do that; you'd just return `position` instead. – T.J. Crowder Dec 31 '16 at 12:09
  • Thanks @T.J.Crowder - helpful for future readers. – Vanquished Wombat Dec 31 '16 at 12:09

0 Answers0