1

I've created the following javascript code:

let myVector = ['one', 'two', 'three', 'four', 'five']

testFunction(myVector)
console.log(myVector)

function testFunction(vector) {
  for (var i = 0, len = vector.length; i < len; i++) {
    vector[i] = vector[i] + ": " + i
  }
  return vector
}

When I execute this code printing the value of myVector I get the following result:

[ 'one: 0', 'two: 1', 'three: 2', 'four: 3', 'five: 4' ]

I don't get how it's possible. I'm probably missing some very fundamental concept of javascript... In my mind, this should only happen if my code were as the following:

let myVector = ['one', 'two', 'three', 'four', 'five']

console.log(testFunction(myVector))

function testFunction(vector) {
  for (var i = 0, len = vector.length; i < len; i++) {
    vector[i] = vector[i] + ": " + i
  }
  return vector
}

On my first sample, I never reasigned a value to myVector... I expected it to print ['one', 'two', 'three', 'four', 'five'] instead of [ 'one: 0', 'two: 1', 'three: 2', 'four: 3', 'five: 4' ]. Why Javascript is changing the value of a parameter that was sent to it? Shouldn't its modifications be valid only inside the function? What would be an alternative way of creating this code in a way that I avoid it to happen?

mplungjan
  • 169,008
  • 28
  • 173
  • 236
raylight
  • 447
  • 4
  • 17
  • you're sending an Array - your function isn't modifying the array, it's modifying the contents of the array – Bravo Jul 29 '21 at 14:14
  • 1
    @Bravo is right. I'll just add that to avoid changing you can make a copy of the array. Something like: `testFunction(myVector.slice())` – Joao Oliveira Rocha Jul 29 '21 at 14:17
  • 1
    The short version is that the value held in variables, passed to functions, etc. for objects (including arrays) is an *object reference* which (effectively) points to the object elsewhere in memory. When you change the object's state, the object itself changes, and you can see that change no matter what copy of the reference you're using. You can see the exact same thing like this: `const a = [1]; const b = a; b[0] = 42; console.log(a[0]); // 42` Afer the `const b = a;` statement, `b` and `a` both have the same value in them -- a reference to the array, elsewhere in memory. – T.J. Crowder Jul 29 '21 at 14:18

0 Answers0