Search code examples
javascriptloopsvariablesvariable-assignmentassignment-operator

Different values for assigned variable in a For Loop and assignment operator, Javascript


I'm new to coding and JavaScript but couldn't find a post that precisely answers this.

The below JS code is to evaluate a factorial of a given number and I don't get why it works in terms of 'num' assignment.

num is used as a parameter, assigned to a new variable "i" and also used in a assignment operator num = num * i or num *= i for short. As a result num changes in the for loop and in the assignment operator but they change as two independent variables. Why? Aren't they pointing to the same thing, num? In other words after evaluating num *= i as 6 why wouldn't the next step in the for loop become i = 6 - 1 ? I feel like I'm missing something obvious...

 function factorialize(num) {
  if (num == 0 || num == 1) {
    return 1;
  }

  for (var i = num -1; i >= 1; --i){
    console.log(i);
    console.log(num);
    num = num * i;
    console.log(i);
    console.log(num);
  }
  return num;
}

factorialize(3);

console output: 2 3

2 6

1 6

1 6

Does this have anything two do with assigning primitive values versus objects, the order of statements or scope of the loop?


Solution

  • Aren't they pointing to the same thing, num?

    No. num is not a thing that can be pointed to, it's a variable - just like i. Both num and i hold a number. They're independent from each other.

    Does this have anything two do with assigning primitive values versus objects?

    Yes. Objects would be (mutable!) things that you can point to. But when assigning to a variable - regardless whether the value is an object or a primitive - then only that variable changes.