I am getting a strange behavior from the following code. The following code is from ajax success, And console.log(positions); inside loop works fine, But outside it gives me nothing.
success: function (data) {
var positions = [];
$.each(data, function (index, value) {
$.each(value, function (index1, value1) {
positions.push({
lat: value1.rider_location.lat,
lng: value1.rider_location.lng,
});
//This works fine | I can get the results. But after commenting out the below line then the last `console.log(positions)` doesn't shows anything.
console.log(positions);
});
});
console.log(positions);
}
The data from the Ajax gives me the following results then i loop through it and assign the values to positions.
Indside the loop gives me the following results :
And outside of loop console.log(positions) gives no exception as well as no results.


positions, so that is what it will print when you log it. Big chance that either yourdataorvalueis empty. Try logging those inside the loop.dataorvalueis an empty collection. Can you show the code where those are populated?console.log(positions)? Insidesuccess:(as in the question) or somewhere else? (ie outsidesuccess:function(data) {) ?positionsoutside of thesuccess:callback (likely even before your ajax call has started), but that's not what you've got in the code in your question, which has been shown to work correctly by two independent fiddles.