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?

5
  • 3
    Your local_var is global. Declare variables with var keyword to make them local: var local_var = "xyz"; Commented May 12, 2010 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"; Commented May 12, 2010 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"? Commented May 12, 2010 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. Commented Jan 27, 2014 at 17:05
  • Is ths your problem? stackoverflow.com/questions/14220321/… Commented Jan 27, 2014 at 17:17

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I have never saw a version declaration. It is definitely not a must

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.