1

So, I wrote the following function:

function getData() {

   var data;
   $(function () {
      $.getJSON('https://ipinfo.io', function (ipinfo) {
          data = ipinfo;
          console.log(data);
     })
   })

console.log(data);
}

The problem with the above is the 2nd console.log doesn't retain the info from the assignment inside the jQuery and logs an undefined object. I'm not exactly sure what is wrong, but I believe it to be something quite minor. However, as much as I've searched online, I haven't found an answer for this particular problem.

Snappy
  • 75
  • 4
  • `.jQuery.getJSON()` returns results asynchronously. You can use `.then()` or `async/await` to use `data` through the code once the jQuery promise object is fulfilled. – guest271314 Nov 05 '17 at 21:06
  • 1
    Possible duplicate of [How to return the response from an asynchronous call?](https://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call) – wscourge Nov 05 '17 at 21:08
  • It's not a scope issue, it's an order of operation issue. The second `console.log` is executed before the first due to the nature of asynchronicity and order. – vol7ron Nov 05 '17 at 21:21

1 Answers1

3

One line: Javascript is Asynchronous.

While many struggle to figure out what it exactly means, a simple example could possibly explain you that.

  1. You request some data from a URL.
  2. When the data from second URL is received, you wish to set a variable with the received data.
  3. You wish to use this outside the request function's callback (after making the request).

For a conventional programmer, it is very hard to grasp that the order of execution in case of JavaScript will not be 1,2 and then 3 but rather 1,3,2.

Why this happens is because of Javascript's event-loop mechanism where each asynchronous action is tied with an event and callbacks are called only when the event occurs. Meanwhile, the code outside the callback function executes without holding on for the event to actually occur.

In your case:

var data;
$(function () {
   $.getJSON('https://ipinfo.io', function (ipinfo) {//async  function's callback
      data = ipinfo;
      console.log(data);//first console output
  })
})

console.log(data);//second console output

While the async function's callback is executed when the data is received from the $.getJSON function, javascript proceeds further without waiting for the callback to assign the value to the data variable, causing you to log undefined in the console (which is the value of the data variable when you call console.log.

I hope I was able to explain that.!

Parijat Purohit
  • 921
  • 6
  • 16