Link to home
Start Free TrialLog in
Avatar of wilson1000
wilson1000

asked on

Set Global Array/Variable from inside a Javascript Function

Hi Experts,

Is there some big secret to setting array or variable values within a function for global access?

I'm using jQuery's getJSON()  to return rows from our database. I then loop through and format the values there-in for display. my problem is I need to access this information later in the script.

I've omitted the var keyword before declaring the value and tested window.string to no avail

How can I achieve global scope for an array or indeed variable from within a function?

Thank you
Avatar of Shinesh Premrajan
Shinesh Premrajan
Flag of India image

Have you tried with the closures in javascript, I think the answer lies there, in a closure the variable willl be available even after the function exit.

Hope this helps
Avatar of imaki06
imaki06

You should declare that variable outside of the function.

Like:

<script type="javascript">
var myarr=new Array();

function myfunc(){
  myarr[0]="first";
}
</script>
Avatar of wilson1000

ASKER

Thank you shinuq, would you clarify what a closure is please?
SOLUTION
Avatar of Proculopsis
Proculopsis

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial

Just for clarification, this is a perfectly acceptable solution:

 window.myArray = ["Hello","World"]

...perhaps it is not clearly understood that, at the outermost level, vars are actually members of the window object and do not cause polution.  You can check this for yourself with the following statements: var G = "!"; alert( window.G );
We will have to agree to disagree on that point.
No worries - glad to help.