0

How can I change the function passed params?

function minus_num(num) {
  num -= 1
}

var num_test = 10

while (num > 0){
  minus_num(num_test)
}

console.log(num)  // there I want to get the 0, but it is infinite loop, because the `num` will have a copy in the function.

How can I change the num_test itself?

sof-03
  • 2,255
  • 4
  • 15
  • 33
  • It's good practice not to change argument inside function body. Preferred option is `return num - 1;` as @CertainPerformance anwser. – qxg Apr 26 '18 at 04:30

3 Answers3

0

You need the function to return the value after being subtracted, and then you need to assign the result of that to num_test.

But num is never explicitly declared in your code. You probably wanted to put num_test in the loop instead:

function minus_num(num) {
  return num - 1
}

var num_test = 10

while (num_test > 0){
  num_test = minus_num(num_test)
}

console.log(num_test)
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

Primitives are passed by value, so you cannot change them in place. Instead you must return the changed value from the function and assign it back to the same variable:

function minus_num(num) {
  num -= 1;
  return num;
}

var num_test = 10

while (num_test > 0) {
  num_test = minus_num(num_test)
}

console.log(num_test);

For your current implementation, you will get an error that num is not defined because you never declared it before the usage.

Please read this post to find out more on variable passing to functions.

31piy
  • 23,323
  • 6
  • 47
  • 67
0

I think it should be

function minus_num(num) {
   return num - 1
}

var num_test = 10

while (num_test > 0){
  num_test = minus_num(num_test)
}

console.log(num_test) 
jiangyx3915
  • 119
  • 3