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?
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/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With