Is there any way to reassign a variable passed into a function?
(Note: I am not asking if there is any way to reassign a variable, whether in global or parent scope. My goal is to create a function that can set ANY variable in ANY scope to a value.
I understand pass by reference and pass by value - and I'm wondering if there is a way to have functions change the memory reference of a variable in any scope (not just a parent scope).
Example:
const setAnyVarTo5 = function(inputVar) {
// set the inputVar to 5, regardless of its type.
inputVar = 5; // this is only setting the local variable inputVar. Even if we passed in a reference to an object, we'd still just be changing inputVar's reference, not x's.
}
let x = 7;
setAnyVarTo5(x);
console.log(x); // 7, but desired output is 5
let y = {};
setAnyVarTo5(y);
console.log(y); // {}
A direct answer to the question is "no". It's also not really a great idea to mutate variables like that.
If you can add more context of what you're trying to achieve, I'd be glad to update the answer with a solution.