4

I'm pretty new to JavaScript and I'm having trouble with some of the properties of variables and functions.

What I want to happen is have a var defined in one function, have the value changed in another, and then have the new value returned to the function where it was originally defined.

Here is a simple sample that I made:

function getIt(){
    var x = 3;
    doubleIt(x);
    alert("The new value is: " + x);
}

function doubleIt(num){
    num *= 2;
    return num;
}

When this is run the alert still displays the original value of x. Is there a syntax to have the value in the original function changed?

1 Answer 1

9

The simplest method would be to assign the result back to the variable

x = doubleIt(x);

Demo: http://jsfiddle.net/ES65W/


If you truly want to pass by reference, you need an object container to carry the value. Objects are passed by reference in JavaScript:

function getIt(){
    var myObj={value:3};
    doubleIt(myObj);
    alert("the new value is: " + myObj.value);
}

function doubleIt(num){
    num.value *=2;
    //return num;
}

Demo: http://jsfiddle.net/dwJaT/

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

1 Comment

I think the fist is more "normal".

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.