Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 537
user1290426 Avatar asked Sep 20 '25 15:09

user1290426


1 Answers

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/

like image 194
mellamokb Avatar answered Sep 22 '25 08:09

mellamokb