0

I have this:

$(document).ready(function(){

pubnub.subscribe ({
    connect: function(m){

        var channelLatestMessages = [];

        pubnub.history({
          channel: broadcastChannel,
          count: 1,
          callback: function (m) {
            if(m[0].length > 0)
            {
                $.each(m[0], function(index, value){
                    channelLatestMessages.push(value);
                });
            }
            //THE NUMBER OF MESSAGE OBJECTS RETURNED IS 2
            //HERE THE OUTPUT IS 2
            console.info(channelLatestMessages.length);
          },
        }); 

        //THE NUMBER OF MESSAGE OBJECTS RETURNED IS 2
        //HERE THE OUTPUT IS 0          
        console.info(channelLatestMessages);
    }
});

});

If I declare:

channelLatestMessages = [];

without the var keyword and after page load issue I in Firebug console:

console.info(channelLatestMessages.length);

the number is 2.

But I get channelLatestMessages.length value of 0 in the code again.

How is this possible???

vlatkorun
  • 127
  • 1
  • 15
  • possible duplicate of [Why is my variable unaltered after I modify it inside of a function? - Asynchronous code reference](https://stackoverflow.com/questions/23667086/why-is-my-variable-undefined-after-i-modify-it-inside-of-a-function) – Bergi Aug 25 '14 at 15:20

1 Answers1

1

Because in the one case you test the length after the event that causes the callback to run is fired and in the other you test it before then.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335