I’m trying to make a function that can take a global variable as an argument and change the value of the variable globally. I tried:
let a = 0
function diffNum(num){
for (let x = 0; x <= 10; x++){
num += x;
return num;
}
I get 55 back when I input a as an argument, but globally, a is still 0. How would I make it so that the global value of a is 55?
Hello!
A couple of things. First, you are missing a }
in your code. Make sure you add the }
such that your return num;
statement is OUTSIDE the if
loop.
Second, you can assign a new value to the global variable outside the function like so:
let globalVariable = 0
globalVariable=1
Knowing that, think about how you would assign the value of a
to num
from your function.
You can update a global variable from inside a function, but you have to reference the the variable name.
let myGlobalVariable = 0;
function changeGlobalVariable(newVal) {
myGlobalVariable = newVal;
}
console.log("Before:");
console.log(myGlobalVariable);
changeGlobalVariable(42);
console.log("After:");
console.log(myGlobalVariable);
I understand what you’re saying, but the goal is to create a function that can take any variable as an argument and change its value. If I were to name a global variable b = 6, I would want the function to be able to change b to 61. If I have to reference the variable inside the function, the function can’t take any variable as an argument.
As long as the variable contains a primitive data type, like a number, you have to reference it. It is the value of the variable that is passed to the function, not the actual variable (primitives are immutable). If it was an object or an array, you would be able to mutate it by “reference” (really bad idea BTW).
const numbers = [1,2,3];
function diffNum(num) {
for (let x = 0; x < num.length; x++) {
num[x] += x;
}
}
diffNum(numbers);
console.log(numbers); // [ 1, 3, 5 ]
You can’t do this without pointers or objects (like arrays). Is this by any chance a C/C++ assignment you’re trying to write in JavaScript? 
No, it was just an experiment I was trying. I would find it useful to be able to have a variable that represents a unique user datum that could be altered by various functions depending on the user’s choices. I guess you would have to make a single function that either has nested functions or a chain of else if statements to accomplish this, but this seems cumbersome to me.
You can do it if you are using non-primitave variables. I.e. You would need to be working with arrays or objects instead of single numbers, but that’s not a huge restriction in practice.