1

Here is one of the similar example

var global=0;
function somefunction()
{
    global++;
}

var temp=global;
function somefunctiontwo()
{
    var x=temp;
}

here I am getting x=0 I want x=1

how can I assign newly assigned value of global variable to x

4
  • where are you calling somefunction to add to global? Commented Jul 28, 2014 at 16:15
  • are you actually calling somefunction before assigning temp = global? Commented Jul 28, 2014 at 16:15
  • somefunction() is called in document.ready() function and somefunctiontwo() is called on click event Commented Jul 28, 2014 at 16:18
  • I assume you want to access the value of the global variable through the temp variable, right? If so, see my answer below. Issue is the 'reference by value' of the number type. Commented Jul 28, 2014 at 16:21

5 Answers 5

3

Use an object as global variable; that will be assigned by reference instead of 'by value' as for the simple (number) type:

var global = { value: 0 };

var temp = global;

in function:

global.value++;

now is:

temp.value == 1
Sign up to request clarification or add additional context in comments.

Comments

0

temp and global refer to two different variables. Assigning to global will not change the value in temp.

Simply change var x=temp to var x=global. It's not clear why you need an intermediate variable.

2 Comments

Tried but still value is 0 i want increamented value of global variable
@jeetZ Then paste the exact code you are executing; the code in your question is incomplete (you never call either function). It's difficult to diagnose code we cannot see.
0
var global=0;
var temp;
function somefunction(){
  global++;
}



function somefunctiontwo() {
    var x=temp;
    console.log(x);
}

somefunction();
temp=global;
somefunctiontwo();

This will give what you expect. Pay attention on how/where you call the functions.

Comments

0

Your structure seems a little off, not sure if this is for a reason we can't see... Will presume it is. Can have a function that resyncs the temp value to global.

function syncGlob(){
    return temp = global;
}

Returns temp as well so you can call it when creating x.

var x = syncGlob();

Comments

0

You're setting the value of temp to global PRIOR to the on ready firing - at this point global is 0. If you increment global at on ready, temp already has a value of 0.

When you click somefunction2 and assign x the value of temp, temp has a value of 0, because at the time of temp initiation, global had a value of 0 NOT 1

Comments

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.