3

A short example:

self.curTabs = null;

$j.getJSON(url)
    .done(function (response) {
        self.curTabs = response.tabs;

        _.each(self.curTabs, function (tab) {
            tab.dataLoaded = true;
        });

        console.log(self.curTabs);
    });

Logical output: [ 0: Object { dataLoaded: true, etc... }, 1: etc... ].

But with this example:

self.curTabs = null;

$j.getJSON(url)
    .done(function (response) {
        self.curTabs = response.tabs;

        _.each(self.curTabs, function (tab) {
            tab.dataLoaded = true;
        });

        console.log(self.curTabs);

        _.each(self.curTabs, function (tab) {
            tab.dataLoaded = false;
        });
    });

Illogical output: [ 0: Object { dataLoaded: false, etc... }, 1: etc... ].

Why the variable get the value false before I assign it?

Thomas Upton
  • 1,853
  • 12
  • 22
GG.
  • 21,083
  • 14
  • 84
  • 130
  • exact duplicate of [Is Chrome's JavaScript console lazy about evaluating arrays?](http://stackoverflow.com/questions/4057440/is-chromes-javascript-console-lazy-about-evaluating-arrays) – Bergi Sep 19 '13 at 16:08

1 Answers1

10

Because console.log isn't synchronous in every implementation. That way it's queued till the main thread finished. In the meantime your new value is set.

schlingel
  • 8,560
  • 7
  • 34
  • 62
  • Yes this is kinda annoying in some cases. – skmasq Sep 19 '13 at 15:43
  • Then how to debug? Into the .done() I call a function and into this function I test `if (tab.dataLoaded) {...}`, the result expected is `dataLoaded == true` but the test is KO. – GG. Sep 19 '13 at 15:45
  • 1
    You could log `JSON.stringify(self.curTabs)` instead. Here's [the MDN documentation](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). – Thomas Upton Sep 19 '13 at 15:46
  • Use a debugger ;-) Or use some let replacement like the stringify approach or one of these: https://developer.mozilla.org/en-US/docs/Web/JavaScript/New_in_JavaScript/1.7?redirectlocale=en-US&redirectslug=JavaScript%2FNew_in_JavaScript%2F1.7#Block_scope_with_let – schlingel Sep 19 '13 at 15:50