How to access Javascript variable values outside of the function

55,531

Solution 1

Since you do NOT have a var in front of the profile=[];, it is stored in the global window scope.

What I suspect is that you forgot to call the profileloader() before using it.

It is good practice is to declare your global variables in an obvious manner, as shown in other answers on this page

It is not considered good practice to rely on side effects.


Commented code to show what is going on, NOTE not recommended method:

This should work. And it does work: DEMO

function profileloader()
{
    profile = []; // no "var" makes this global in scope
    profile[0] = "Joe";
    profile[1] = "Bloggs";
    profile[2] = "images/joeb/pic.jpg";
    profile[3] = "Web Site Manager";
}
profileloader(); // mandatory
document.write("Firstname is: " + profile[0]);

Solution 2

declare it outside the function so the outside scope can see it (be careful of globals though)

var profile = [];
function profileloader(){
    profile[0] = "Joe";
    profile[1] = "Bloggs";
    profile[2] = "images/joeb/pic.jpg";
    profile[3] = "Web Site Manager";
}

or have the function return it:

function profileloader(){
    var profile = [];
    profile[0] = "Joe";
    profile[1] = "Bloggs";
    profile[2] = "images/joeb/pic.jpg";
    profile[3] = "Web Site Manager";
    return profile;
}

var myprofile = profileloader(); //myprofile === profile
Share:
55,531
GeordieDave1980
Author by

GeordieDave1980

University Student doing Internet Computing!

Updated on July 23, 2022

Comments

  • GeordieDave1980
    GeordieDave1980 almost 2 years

    I've been banging my head off a brick wall with this one and another all nighter with no success. What I would like to do is have access to the values set in an array within a function but outside of that function. How could this be done? For example:

    function profileloader()
    {
        profile = [];
        profile[0] = "Joe";
        profile[1] = "Bloggs";
        profile[2] = "images/joeb/pic.jpg";
        profile[3] = "Web Site Manager";
    }
    

    I would then further down the page within a paragraph tag have something like:

    document.write("Firstname is: " + profile[0]);
    

    Obviously that would be contained with in the script tag but all i'm getting is an error on the console stating: "profile[0] is not defined".

    Anyone got any ideas where I'm going wrong? I just can't seem to figure it out and none of the other solutions I've seen when passing values from either function to function or outside of a function, have worked so far.

    Thank you to anyone who can help me with this, its probably something simple I've missed!