chocolattes
chocolattes

Reputation: 60

How do I change the value of any global variable inside of a function?

I'm using javascript. I want to have a function that can change the value of a given global variable. My code has to have the following structure:

function change(variable_name, new_value){
    //Code to make it work!
}

and I want the function to work like this:

var x = 0;
change(x,2);

and at this point the variable x should be equal to 2.

Thanks and sorry for my english!

Upvotes: 0

Views: 758

Answers (1)

Clyde Lobo
Clyde Lobo

Reputation: 9174

You should pass the variable name as a string

function change(variable_name, new_value){
    window[variable_name] = new_value
}

var x = 0;
change('x',2); //  pass the variable name as a string, instead of the variable

Upvotes: 4

Related Questions