0

I'm currently learning js and stumbled upon this to me weird behavior. I probably missing something fundamental here, but i can't find the answer.

I have a function that modifies an array and returns it. If i print that out the original array gets modified, even though it's a constant.

const arr = [5, 9, 7, 1, 8, ];

function test(arr) {
  const strings = ['qwe', 'asd'];
  arr.splice(1, 0, ...strings);
  return arr
}

console.log(test(arr))
console.log(arr)
console.log(test(arr))
console.log(arr)
console.log(test(arr))
console.log(arr)

Output shows that the original array gets bigger everytime. I was expecting that it is the same output everytime.

DecPK
  • 24,537
  • 6
  • 26
  • 42
Codehauk
  • 53
  • 1
  • 3
  • 2
    `const arr` means identifier `arr` _can't be re-assigned_; it doesn't means you can't mutate the object (array) that is referred to by `arr`. Re-assignment of `arr` and mutation of the actual array are two different things. `const` is related to re-assignment. – Yousaf Sep 15 '21 at 10:30
  • 1
    Notice, that `arr` in the function is not the same `arr` variable you've defined in the global scope, function arguments create local variables to the function. If you'd do `arr = 1` in the function, that will work (the global `arr` won't change). – Teemu Sep 15 '21 at 10:39
  • `const` creates an immutable _binding_, not an immutable value. [Google](//google.com/search?q=site%3Astackoverflow.com+js+const+array+is+not+immutable) finds more related posts: [Keyword 'const' does not make the value immutable. What does it mean?](/q/42833540/4642212), [JavaScript ES6 `const a = {}` is mutable. Why?](/q/34983693/4642212). – Sebastian Simon Sep 15 '21 at 10:52

1 Answers1

1

A const means you cannot reassign to it like this

const arr = [1, 2, 3];
arr = [5, 4]; // You cannot do this that's const

other than that you can modify the array contents

Jack
  • 788
  • 3
  • 13
  • Thank you, that makes sense. But i still don't understand why the function call inside the log() is writing changes the global arr. Shouldn't the arr in the function context be in another scope? If i rename the function variable, i get the same result – Codehauk Sep 15 '21 at 10:33
  • 3
    That's because when you pass array or even object (array is also object) you pass the reference to it (memory location of that) not a new copy so whatever you do in function affects everywhere the same array is used – Jack Sep 15 '21 at 10:35
  • For more theory about it, google 'stack vs heap' . It is a common thing across a lot of (popular) languages . – Wojtek322 Sep 15 '21 at 10:41
  • 1
    If anyone cares, i found the problem: As jack said, it was because i referenced it as an object. I used let neWarr = [...arr] to copie it to a new object – Codehauk Sep 15 '21 at 11:40