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.

1

2 Answers 2

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.

-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.

1
  • 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 :) Jan 4, 2014 at 22:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.