0

Here's my json file:

{
  "info": {
  "title": "LRR Test map",
  "width": 50,
  "height": 50
 }
}

And here's my JavaScript code:

var mapInfo = $.getJSON('levels/test.json').done(function(data){mapInfo = data.info;});
alert(mapInfo.title);

Problem is, I get an alert labeled undefined. Well, when I open up my developer console (I'm on Chrome) and type in mapInfo I get this output:

Object {title: "LRR Test map", width: 50, height: 50}

And when I type in alert(mapInfo.title); it does alert my Lrr Test map.

Why can I access my variable through developer console, but I cannot call it out in my code? This is really uncommon for me, and appeared for the first time in my quite large project.

Kajcioch
  • 175
  • 1
  • 8
  • 1
    `$.getJSON` is **asynchronous**. The issue has nothing to with scope but with timing. You are calling `alert(mapInfo.title);` *before* `mapInfo = data.info;` has happened. `$.getJSON` also doesn't return what you seem to think it does. – Felix Kling Dec 21 '16 at 18:31
  • @FelixKling Thanks a lot!! – Kajcioch Dec 21 '16 at 18:34
  • *"Why can I access my variable through developer console, but I cannot call it out in my code?"* By the time you type something in the console, `mapInfo = data.info;` has happened already. The asynchronous operation (the Ajax request) won't take much time, but because of the way JavaScript is designed, the `alert` in your code will *always* be executed before the `.done` callback was executed. – Felix Kling Dec 21 '16 at 18:34

0 Answers0