Matei Gheorghiu
Matei Gheorghiu

Reputation: 45

Array Scope Issue

I've looked around for hours and I honestly don't understand why this is not working. I though I understood scope, but I think this has something to do with the callback on the .popular method. Any advice?

var filters = [];  //Global

INSTAJAM.media.popular(function(popular){

    for (i in popular.data){
        filters.push(popular.data[i].filter); //Pushing to Global
    }

    console.log(filters); //Works fine

});

console.log(filters); //Empty array

Upvotes: 0

Views: 67

Answers (2)

jfriend00
jfriend00

Reputation: 707218

These are the reasons I can think of for why your second console.log(filters) would be empty:

  1. INSTAJAM.media.popular is likely an asynchronous function (it calls it's callback sometime later probably as the result of an ajax call) and when you do the second console.log(filters);, the ajax call has not yet completed so your callback that populates the global filters variable has not yet been called or run.
  2. var filters = []; is not really global.
  3. There's another variable named filters within scope so you aren't actually modifying the global one.

Based on the structure of INSTAJAM.media.popular that takes a callback, my guess is #1. Asynchronous javascript means that things do not happen in serial execution order. Instead, you call something like INSTAJAM.media.popular(fn) and sometime later, the callback is called when the ajax call completes. This means that code located immediately after you call INSTAJAM.media.popular(fn) cannot use the results of that call. Instead any code that wants to use those results must be in the callback itself or called from the callback.

Upvotes: 2

CrayonViolent
CrayonViolent

Reputation: 32532

you can reference window.filters

Upvotes: 0

Related Questions