2

I am getting some weird behaviour with the following, it shows an array length of 0 eventhough printing it right before that shows that there clearly is a length greater than 0:

var getTopSelection = function(callback) {
    var topSelection = [];
    for(var i=0; i < markers.length; i++) {
        if(markers[i].map !== null) {
            var stationID = markers[i].id;
            getTrips(stationID, globalFromDate, globalToDate, function(response) {
                topSelection.push({
                    StationID: stationID,
                    Trips: response
                });
            }, function(error) {
                console.log(error);
            })
        }
    }
    callback(topSelection);
};

getTopSelection(function(response) {
            console.log(response); //115
            console.log(response.length); //116
})

And this is shown in the inspector, the "length: 42" belongs to line 115.

enter image description here

Question: Why does it show a length of 0 eventhough it clearly says it has a length of 42 one line before?

Community
  • 1
  • 1
ffritz
  • 2,180
  • 1
  • 28
  • 64
  • is the response a json object? – Emad Ha Jun 08 '17 at 10:27
  • are you sure response is an array and not an object? – Manish Jun 08 '17 at 10:27
  • @Manish I added the code above which populates the response. It should be an array. – ffritz Jun 08 '17 at 10:29
  • 1
    Maybe your response isn't populated at the time it's printing to the log. Similar to this question: https://stackoverflow.com/questions/38660832/console-log-of-element-children-shows-0-length-but-has-three-entries-when-expand – Niklas Jun 08 '17 at 10:29
  • @Niklas Is everything you place after a for loop just exectued before the loop finishes? Haven't figured out why it's so difficult to just wait til it finishes. – ffritz Jun 08 '17 at 10:31

3 Answers3

4

console.log is not synchronous.

Your console.log statements appear after you have called getTrips but before the getTrips callback has fired.

Effectively, you are trying to return the response from an asynchronous call.

response is an object. Objects in JS are always referenced. You are logging that reference, and then the object gets updated with the new values (and the new length) when the getTrips callbacks fire. The new object is reflected in the console.

response.length is a number. You are logging it. Number values are not references. It is 0 because at the time you called console.log it was 0. The display doesn't update when the value changed because is a number and not an object.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thanks. So in the example above, I do need to make use of a (non-zero) length of that object, and since any for loop there depending on the length will not fire, do I need to make use of an async helper library or something like this? Thought this would be rather simple. – ffritz Jun 08 '17 at 10:36
  • Yes, you need to wait until all the `getTrips` calls have been resolved. I'd try to turn them into Promises and then use `Promise.all`. – Quentin Jun 08 '17 at 10:40
1

So what actually happens is that when you log your response it actually having length as 0. But after the asynchronous response is returned it has 42 items but length being a property is logged as number. But your response being an object is logged initially with zero items. But when the actual response is received the reference to the response object is updated and you see that the response is having 42 items and length is also 42. The below code is an example for that that to show after the setTimeout is called the logged response is updated in the console.

var getTopSelection = function(callback) {
    var topSelection = [];
    markers=[1,2,3,4,5,6,7,8,9];
    for(var i=0; i < markers.length; i++) {
        if(markers[i].map !== null) {
            var stationID = markers[i].id;
            getTrips(stationID, function(response) {
                topSelection.push({
                    StationID: i,
                    Trips: response
                });
            }, function(error) {
                console.log(error);
            })
        }
    }
    callback(topSelection);
};

function getTrips(station,fun){
setTimeout(function(){
 fun(["trip1","trip2","trip3"]);
},1000)
}
getTopSelection(function(response) {
            console.log(response); //115
            console.log(response.length); //116
})

Try executing this snippet(have modified accordingly to show what actually happens) in a Fiddle here. And observe the output in console as in stackoverflow snippet result it wont be visible. Here is snap of the Console Output

enter image description here

Hope it helps :)

Manish
  • 4,692
  • 3
  • 29
  • 41
-2

Array Length returns 0

It seems you are trying to find the length of an object, not an actual array.

Ben Brookes
  • 419
  • 4
  • 15
  • You can see the `length` property having a different value from the previous `console.log` statement in the image in the question. – Quentin Jun 08 '17 at 10:28