How to access variable outside the function in javascript

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!

asked May 23, 2012 at 5:39

GeordieDave1980GeordieDave1980

5694 gold badges10 silver badges24 bronze badges

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]);

answered May 23, 2012 at 5:49

mplungjanmplungjan

159k27 gold badges167 silver badges225 bronze badges

6

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

answered May 23, 2012 at 5:40

3

Scope in JavaScript defines accessibility of variables, objects and functions.

There are two types of scope in JavaScript.

  1. Global scope
  2. Local scope

Global Scope

Variables declared outside of any function become global variables. Global variables can be accessed and modified from any function.

<script>

    var userName = "Bill";

    function modifyUserName() {
            userName = "Steve";
        };

    function showUserName() {
            alert(userName);
        };

    alert(userName); // display Bill
    
    modifyUserName();
    showUserName();// display Steve

</script>

In the above example, the variable userName becomes a global variable because it is declared outside of any function. A modifyUserName() function modifies userName as userName is a global variable and can be accessed inside any function. The same way, showUserName() function displays current value of userName variable. Changing value of global variable in any function will reflect throughout the program.

Please note that variables declared inside a function without var keyword also become global variables.

<script>

    function createUserName() {
        userName = "Bill";
    }

    function modifyUserName() {
        if(userName)
            userName = "Steve";
    };

    function showUserName() {
        alert(userName);  
    }
    
    createUserName();
    showUserName(); // Bill 

    modifyUserName();
    showUserName(); // Steve 

    
</script>

In the above example, variable userName is declared without var keyword inside createUserName(), so it becomes global variable automatically after calling createUserName() for the first time.

A userName variable will become global variable only after createUserName() is called at least once. Calling showUserName() before createUserName() will throw an exception "userName is not defined".

Local Scope

Variables declared inside any function with var keyword are called local variables. Local variables cannot be accessed or modified outside the function declaration.

<script>
    
    function createUserName() {
        var userName = "Bill";
    }

    function showUserName() {
        alert(userName);
    }

    createUserName();
    showUserName(); // throws error: userName is not defined

</script>

How to access variable outside the function in javascript
Function parameters are considered as local variables.

In the above example, userName is local to createUserName() function. It cannot be accessed in showUserName() function or any other functions. It will throw an error if you try to access a variable which is not in the local or global scope. Use try catch block for exception handling.

Some tips..

If local variable and global variable have same name then changing value of one variable does not affect on the value of another variable.

var userName = "Bill";

function ShowUserName()
{
    var userName = "Steve";

    alert(userName); // "Steve"
}

ShowUserName();

alert(userName); // Bill

JavaScript does not allow block level scope inside { }. For example, variables defined in if block can be accessed outside if block, inside a function.

Function NoBlockLevelScope(){
    
    if (1 > 0)
    {
        var myVar = 22;

    }

    alert(myVar);
}

NoBlockLevelScope();

  1. JavaScript has global scope and local scope.
  2. Variables declared and initialized outside any function become global variables.
  3. Variables declared and initialized inside function becomes local variables to that function.
  4. Variables declared without var keyword inside any function becomes global variables automatically.
  5. Global variables can be accessed and modified anywhere in the program.
  6. Local variables cannot be accessed outside the function declaration.
  7. Global variable and local variable can have same name without affecting each other.
  8. JavaScript does not allow block level scope inside { } brackets.

Want to check how much you know JavaScript?

How do you use a variable outside a function?

Use the object attribute syntax to access a variable outside of a function. In a function named func , use the syntax func. variable = value to store value in variable as an attribute of func . To access value outside of func , use func() to run func , then use the syntax function_name.

How do you access a variable outside a block in JavaScript?

Read about the let declaration in the JavaScript documentation about declarations and statements. You use blocks to limit the scope of a variable. The main reason of a block is that x is not accessible outside the block. If you want to access a variable outside a bock, declare it outside the block.

Which variable declared outside a function in JavaScript?

A JavaScript global variable is declared outside the function or declared with window object. It can be accessed from any function.

How do you access variables within a function?

So the easiest way to make your variable accessible from outside the function is to first declare outside the function, then use it inside the function..
function one(){ var a; function two(){ a = 10; return a; } return a; }.
var a; Parse. doSomething(). ... .
var a; query..