0

Assume we have a code:

const someNumber = 3;
const someArray = [1, 2, 3];

function changeArray(sampleArray, numberToPush) {
  sampleArray.push(numberToPush);
  return sampleArray;
}

function incrementNum(number) {
  number++;
  return number;
}

const modifiedArray = changeArray(someArray, 5);
const incrementedNum = incrementNum(someNumber);

console.log(someNumber, incrementedNum, someArray, modifiedArray, ) // 3, 4, [1, 2, 3, 5], [1, 2, 3, 5]

I don't understand why it is working this way. If we put a number as an argument and increment it, then the original number is not affected. If we put an array as an argument and push some additional number, then the original array is affected.

I know that I can create a copy of an array inside a function, but I don't understand this behavior - why original array as an argument is affected but a number as an argument is not affected?

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
sebastian
  • 3
  • 1
  • `number++` is the same as `number = number + 1`. You are not mutating the existing number, as is the case with the array value, you are creating a new number value. Primitive values are *immutable*. – Felix Kling Mar 03 '21 at 11:17
  • Another way to look at it: a variable like `someNumber` or `someArray` is like a named blackboard. In the case of `someNumber = 3`, the primitive value `3` is written on the blackboard, and when you pass `someNumber` to a function, you're actually passing the 3. However for `someArray = [1, 2, 3];` , the `[1, 2, 3]` is written into a free part of the RAM, and the address of that location is then written on the `someArray` blackboard. Passing `someArray` to a function passes the *address*, and thus you can now change the array at that RAM location inside your function (no copy was created) –  Mar 03 '21 at 11:33
  • Oh, I had a wrong understanding of passing arguments to functions. I thought that all arguments are just copied when they are passed as arguments. So it is a similar situation with an object, we are passing the address of that location and it can be changed because we are referring to some place in the memory. Thanks for the explanation I think now I have better understanding of how functions work. – sebastian Mar 03 '21 at 12:06

0 Answers0