Changing variable in another function in JavaScript

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?

Answers:

Answer

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/

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us

©2020 All rights reserved.