0

I know that passed arguments inside function are copies of data passed to the function.

But why is it that you can change arrays and objects but not strings and numbers by changing them as arguments inside function ?

Array example:

const numbers = [1, 2]

const change = (arg) => {
  arg.push(3)
};

change(numbers);

console.log(numbers); // [1,2,3] - arr changed!

Number example:

const number = 2

const change = (arg) => {
  arg = arg + 1
};

change(number);

console.log(number); // 2 - number didn't change
Johnexe
  • 83
  • 1
  • 9
  • @decpk The actual reason is that `arg = arg + 1` performs a reassignment of `arg`, which is scoped to the function. It doesn’t affect `number` because it has nothing to do with `number`. `arg = [1, 2, 3];` wouldn’t affect the `numbers` array either. Just like `let x = 1; let y = x; y = 2;` doesn’t magically change `x` to `2`. Furthermore, there is no way to _mutate_ a primitive with a method call as primitives are immutable. – Sebastian Simon Apr 10 '21 at 11:24
  • 1
    @decpk Nothing in JS is passed by reference, everything is passed by value. – Teemu Apr 10 '21 at 11:27
  • Additional possible duplicate target: [Why won't my function change object value?](https://stackoverflow.com/q/31571448/4642212). – Sebastian Simon Apr 10 '21 at 11:28

0 Answers0