1

I am a javascript newbie and trying this code in javascript(using jQuery) :

$(document).ready(function() {
var nodes=[];
$.getJSON('/get/data', function(data) {
            nodes.push(data);
        });
//debugger
console.log(nodes);
console.log(nodes[0]);
});

This is what I see in console:

[ ]
undefined

But when I uncomment //debugger and run it, I get these results:

  []
  []
  []
 [[Object { id=10,  label="foo"}, Object { id=9,  label="bar"}, 43 more...]]
 [Object { id=10,  label="foo"}, Object { id=9,  label="bar"}, ...]

What is going on? I can't understand how activating the debugger can affect a variable and make it defined or undefined. By the way, this is just part of a larger script so it may be a factor.

jrook
  • 3,459
  • 1
  • 16
  • 33

1 Answers1

1

This is an asynchronous function, so nodes will not be populated till after your callback gets run. Try this:

var nodes=[];
 //this "function(data)" is a callback to be executed when you get your data back
 $.getJSON('/get/data', function(data) {
     nodes.push(data);
     console.log(nodes); //<--this now has data!
     console.log(nodes[0]);
});
KJ Price
  • 5,774
  • 3
  • 21
  • 34