How can I modify the variables passed outside the function?

excuse me, how can I modify the variable passed in outside the function, not the one that modifies the copy?

function minus_num(num) {
  num -= 1
}

var a = 10

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

console.log(a)  // 0
Mar.06,2021

function minus_num(num) {
  return num - 1
}

var a = 10

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

console.log(a)  

function minus_num(num) {
  return num - 1
}

var a = 10

while (num > 0){
  a = minus_num(num)
}

console.log(a)  

the variable passed in through the function modification, one is not to define the change inside the function, so that the function finds the change and modifies it through the scope.
another is to assign a value to a change variable through the return value of the function.
this is because when a function passes parameters, the basic type is passed by value. The value of an in the title is copied to num, but the change of num will not affect the change of a. This is not quite the same as writing code like c or cPP.
so the code can do this, but it is not recommended to write functions this way. By returning the value, someone answered before, do not write.

function minus_num(num) {
    a -= 1
}

var a = 10

while (a > 0) {
    minus_num()
}

console.log(a)

basic type [number,string,boolean] cannot be modified in the function. Reference types can be used, such as object,array


to pass variables of reference type to the function, and the function does not assign values directly. If you just modify it, you can achieve the desired effect.
the basic type variable is passed in a copy, and the reference type variable is passed in the reference address


pass parameters in the way of objects:

function minus_num(obj) {
  obj.num -= 1
}

var obj = {num: 10};
var a = 10

while (obj.num > 0){
  minus_num(obj)
}

console.log(a, obj) 
Menu