Update global variable from function in javascript

Here's the situation:

I have one function that has a local variable. I would like to assign this value to a global variable and us this value in another function.

Here is the code:

global_var = "abc";

function loadpages()
{
    local_var = "xyz";
    global_var= local_var;
}

function show_global_var_value()
{
    alert(global_var);
}

      

I call the show_global_var_value () function on the HTML page, but it shows value = "xyz" and not "abc"

What am I doing wrong?

+2


a source to share


1 answer


What you need to do besides declaring local variables with a statement var

as stated earlier is the instruction let

provided in JS 1.7

var global_var = "abc";

function loadpages()
{
    var local_var = "xyz";
    let global_var= local_var;
    console.log(global_var); // "xyz"
}

function show_global_var_value()
{
    console.log(global_var); // "abc"
}

      

Note: to use JS 1.7 for now (2014-01), you must declare the version in the script tag:



<script type="application/javascript;version=1.7"></script>

      

However, let

it is now part of the ECMAScript Harmony standard, so it is expected to be fully available in the near future.

+1


a source







All Articles