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?
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?
Share Improve this question edited May 12, 2010 at 14:02 Eli Courtwright 194k69 gold badges223 silver badges257 bronze badges asked May 12, 2010 at 13:56 Mike_NCMike_NC 211 gold badge1 silver badge2 bronze badges 5-
3
Your
local_var
is global. Declare variables withvar
keyword to make them local:var local_var = "xyz";
– el.pescado - нет войне 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 withvar
to make it local:val local_var = "xyz";
– RoToRa 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 setglobal_var
to "xyz"? – Pointy Commented May 12, 2010 at 14:04 - I'm pretty sure that he's ing 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. – user2509223 Commented Jan 27, 2014 at 17:05
- Is ths your problem? stackoverflow./questions/14220321/… – John Dvorak Commented Jan 27, 2014 at 17:17
1 Answer
Reset to default 1What 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.