1

I'm trying to define a variable that has been chosen in the arguments of a function but it won't change the variable I'm using in the argument.

My code:

var x = "nothing yet!";

function changeValue(variable) {
    variable = "x";
}

changeValue(x);
console.log(x);

When I run it through the console, it just comes out as "nothing yet!" when I want it to come out as 'x'.

Any help on resolving this would be very helpful.

  • You might also want to check out this answer in a similar thread: http://stackoverflow.com/a/7744623/2634696 – ds1 Jan 04 '14 at 22:14

2 Answers2

2

In JavaScript strings are primitive value types. You can't change them from within a function like that.

They are also immutable. Changing the string in your example is like changing the number 2 :)

To emphasize that, to JavaScript - what you're doing is kind of like:

function makeTwoThree(two){
    two = 3;
}
var two = 2;
makeTwoThree(two); // two is passed by value since it's a value type.

You should return it instead:

function changeValue(variable) {
    return "x";
}
variable = changeValue(variable);

Alternatively, you can wrap it in an object and pass the object which would let you change the reference. However, keep in mind you're not changing the string here, but replacing it.

Benjamin Gruenbaum
  • 270,886
  • 87
  • 504
  • 504
-1

You should reference it as global variable, by doing this:

var x = "nothing yet!";

function changeValue(variable) {
    window[variable] = "x";
}

changeValue("x");
console.log(x);

That will put x in your console. This works because the variable x is defined in the global scope (outside any functions). You could also do this, for if it also needs to work outside the global scope, so inside a function:

(function() {
    var x = "nothing yet!";

    function changeValue(variable) {
        this[variable] = "x";
    }

    changeValue("x");
    console.log(x);
})()

The this in that code refers to the scope it's called from, so in this case, this[variable] just gets the variable x from the function from which it was called.

Joeytje50
  • 18,636
  • 15
  • 63
  • 95
  • 1
    This is not what OP wanted to accomplish, you're passing the variable _name_ to the function now and not the variable. Also, if the above code is not in the global scope this will not work. Also, globals are evil :) – Benjamin Gruenbaum Jan 04 '14 at 22:15