What is happening is that the setVariableValue()
function only receives the value of the variables test
, test2
and test3
. So within the function, its operation is executed successfully, but over variables that will cease to exist once the function returns (they will be out of scope).
So, we usually call a function, already assigning the result to the variable itself:
test = setVariableValue(test, 20); // atribui o resultado a 'test'
In this case, your function should have a return
:
function setVariableValue(variable, value) {
// return necessário para que a função retorne algum valor!
return variable * value;
}
var test = 10;
test = setVariableValue(test, 20);
document.writeln(test); // Resultado: 200
A second way to solve - Use the variable itself within the function:
var test;
function setVariableValue(value) {
test = value;
}
setVariableValue(12);
document.writeln(test); // Resultado: 12
And a third way - Using objects:
function setVariableValue(variable, value) {
variable.value = value;
}
var test = [], test2 = [], test3 = [];
setVariableValue(test, 20);
setVariableValue(test2, "Ola");
setVariableValue(test3, 1000);
document.writeln(test.value);
document.writeln(test2.value);
document.writeln(test3.value);
As objects, what is passed to the function ends up being a reference, and when changing an attribute of this object, the change persists.