1

Why is it, it only works within the function scope while I have this declared it globally

testing = [];

function func1(){
  //some codes here that fills the "testing" array... 
}
//I want to display here the new array values.. 

watch it on JSFiddle

  1. click on the button
  2. inspect element the output,
  3. on the console

    I need the "testing" array on another function. how will I use it then?

6
  • 1
    possible duplicate of global array values can't be accessed inside for loop Commented Jan 31, 2013 at 23:04
  • @Pointy It's not a duplicate, that guy had an empty array he didn't fill. This guy filled his array asynchronously and tried to access it before it was filled. Commented Jan 31, 2013 at 23:07
  • Your testing array is accessible to other functions. The reason nothing is printed in the "outside function scope" log is because it is empty at that point Commented Jan 31, 2013 at 23:07
  • 1
    @BenjaminGruenbaum: Except they are the same guy, and it looks suspiciously like the same code sample (and they were asked less than an hour apart). Commented Jan 31, 2013 at 23:09
  • @mellamokb oh lol, I wasn't aware of that ^_^ my bad. It's still a different question though. Commented Jan 31, 2013 at 23:09

2 Answers 2

1

Your array gets populated after this console.log("outside function scope :\n"+testing); gets called.

Ignoring all the problems in your jsfiddle, the reason you're not seeing the behavior you expect is because the event that causes the array to be populated is asynchronous where the code that displays it outside the scope gets executed right away.

Sign up to request clarification or add additional context in comments.

Comments

1

Notice the order in which the messages appear in the console. When page loads:

outside function scope :

After clicking the button:

inside function scope :
RSdKmX2BH7o,EWMLMc3ES3I,SIXwlxhjaKY,RIKTFn5ALE8,acp8TbBPVos,6GpKR4-TLoI,XLKLkTnKRwg,6WPELkw5kD0

The code outside of any function scope runs immediately as soon as the page is loaded, but the code that is populating testing only runs after clicking the button.

3 Comments

can you suggest a possible solution? I also thought of that and have tried to assign the "Testing" variable to a new varible that is also global. but same results.
What do you need to do with the results? Just do it after they've been loaded.
I need the array data to a different function.. can you help with this? jsfiddle.net/aKX87/3 I am trying to dynamic result from this static one -- > jsfiddle.net/9zqL6/3

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.