0

Here is the code:

var num = 3

myFunction(num)

function myFunction(aNumber)
{
    aNumber = 20
}

console.log(num)

it still says that 'num' is 3 and I was wondering why?

  • 1
    JS doesn't have pointers. You're assigning `20` to the `aNumber` parameter, which received the current value of `num`, but is otherwise unrelated to `num`. –  Apr 17 '17 at 13:31
  • `myFunction(num)` *reads* the value 3 from `num` and passes the value (not the variable) into `myFunction`. `myFunction` receives that value in the parameter `aNumber`. `aNumber = 20` stores the value 20 in `aNumber`, which has no effect whatsoever on `num`, since the function doesn't know anything about `num` from the call (it does via other means, but that's nothing to do with the `aNumber` parameter). – T.J. Crowder Apr 17 '17 at 13:35
  • `myFunction` *can* update `num`, by doing `num = 20` directly, because `myFunction` is a closure over the context in which `num` is defined. If it *weren't* a closure over the context where `num` is defined, it wouldn't be able to update it directly. – T.J. Crowder Apr 17 '17 at 13:35
  • The *usual* way to update a variable via a function is to have the function return the new value: `num = myFunction(num)` and `function myFunction(aNumber) { return aNumber + 10; }` for instance, which adds 10 to the value passed in and returns that new value. In the above, that would end up returning 13, which would then be assigned to `num`. – T.J. Crowder Apr 17 '17 at 13:36

1 Answers1

0

You dont have to pass global variables into functions to reassign them.

function myFunction() { 
  num = 20
}
console.log(num);
Dan Philip Bejoy
  • 4,321
  • 1
  • 18
  • 33
  • True, but this assumes that the function always wants to mutate the `num` variable. Given the original code, it would be able to mutate any variable passed in (if it worked that way). –  Apr 17 '17 at 13:39