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.
CodePudding user response:
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