2

Here is the situation:

I have one function which has local variable. I would like to assign that value to global variable and us it's 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'm calling show_global_var_value() function in the HTML page but it shows the value = "xyz" not "abc"

What am I doing wrong?

Eli Courtwright
  • 186,300
  • 67
  • 213
  • 256
Mike_NC
  • 21
  • 1
  • 1
  • 2
  • 3
    Your `local_var` is global. Declare variables with `var` keyword to make them local: `var local_var = "xyz";` – el.pescado - нет войне May 12 '10 at 13:59
  • 1
    I don't understand where your problem is. It's doing exactly what you seem to want. BTW, `local_var` is not local. You need to declare it with `var` to make it local: `val local_var = "xyz";` – RoToRa May 12 '10 at 14:02
  • Your question makes no sense. Describe your reasoning as to why you think the alert should show "abc". Specifically, what is it that you think the `loadpages` function is supposed to do if it's not to set `global_var` to "xyz"? – Pointy May 12 '10 at 14:04
  • I'm pretty sure that he's coming from an other programming language, hence the difficulty of describing the desired behaviour. If thats the case and the desired behaviour is to set the global variable to a different value but only for the local scope, than see my answer below. –  Jan 27 '14 at 17:05
  • Is ths your problem? http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-ajax-call – John Dvorak Jan 27 '14 at 17:17

1 Answers1

1

What you need to do apart from declaring local variables with var statement as other pointed out before, is the let statement introduced 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 at the moment (2014-01) you must declare the version in the script tag:

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

However let is now part of ECMAScript Harmony standard, thus expected to be fully available in the near future.