The challenge & explanation.
I want to reassign a global variable when it's passed to a function as an argument but here is the catch I don't want to reference it directly inside of the function so here is the result I want to occur.
let number = 5;
function changesVariable() {
number = 3;
}
changesVariable();
console.log(number); // 3
but I don't want to directly add "number" inside of the function I want a behavior like below I want to pass "number" as an argument and then the function reassigns it by that.
let number = 5;
function changesVariable(n) {
n = 3;
}
changesVariable(number);
console.log(number); // here it returns 5 but would like to see 3
BTW I know the above code is wrong it's here only to explain the concept.
How I tried to solve it
so below are some examples that how I approach it. but their arent the answer.
function changesVariable(n) {
arguments[0] = 3;
}
changesVariable(number);
console.log(number); // still 5
we can do something like:
function changesVariable(n) {
return (arguments[0] = 3);
}
number = changesVariable();
console.log(number);
but I am seeking an answer with these conditions:
- reassign the "number" by passing it to function as an argument.
- I don't want to use "number" variable directly inside the function.
If all the text above didn't help
I want to create a Utils function that you can pass different global variables to it and it will reassign them that's why I have this approach I want the function to be reusable like:
changesVariable(number1);
changesVariable(number2);
changesVariable(number3);
changesVariable(number4);