I know Javascript works with parameters by value for numbers when passing them to a function. So, if i had a function that resolves something but apart from that, needs to change the value of 2 variables from outside passed as parameters, how can i get that done? is there even a way?
Asked
Active
Viewed 26 times
-1
-
Perhaps you could provide an example of what you're trying to do? Parameters are pass-by-value. The function can update variables that are in scope, even if they're not function parameters. It can return the new values and consuming code can update whatever it wants. The parameter can be an object and the function can mutate that object. There may be other options as well. But what's best for you depends on what you're doing. Barring any compelling reason otherwise, I would by default recommend that the function returns the values and consuming code does what it wants with them. – David Nov 22 '22 at 16:18
-
for example: "substract 1 from a number until it reaches 0 and increment a counter of times you substraced" if i wanted to do that in a function, i couldn't modify both of the values, so when i return if i did "counter= aFunction(counter,number)" and a "return counter" inside, i would be only modifying the counter and the number would still be as if i didn´t subsctract anything from it after coming back. – Utam Nov 22 '22 at 16:38
-
Why can't your modify both values? Are you concerned about what you're returning? Can you return them in an Object? `return {number:number,counter:counter};` – mykaf Nov 22 '22 at 16:49
-
Thanks! Working with an object instead of isolated variables was the solution. – Utam Nov 22 '22 at 17:27
1 Answers
0
Variables outside a function can be changed directly inside that function as long as they are in the same file. For example something like this should work.
var test1 = 0
var test2 = 3
changeOutsideVariable(test1 + 1, test2 + 2)
/* Prints "1, 5" */
console.log(test1 + ", " + test2)
function changeOutsideVariable(para1, para2) {
test1 = para1
test2 = para2
}

MNTL
- 11
- 3