function bubbleSort(toSort) {
let sort = toSort;
let swapped = true;
while(swapped) {
swapped = false;
for(let i = 0; i < sort.length; i++) {
if(sort[i-1] > sort[i]) {
let temp = sort[i-1];
sort[i-1] = sort[i];
sort[i] = temp;
swapped = true;
}
}
}
return sort;
}
let asdf = [1,4,3,2];
let asd = bubbleSort(asdf);
console.log(asdf, asd);
The output to this code is: [ 1, 2, 3, 4 ] [ 1, 2, 3, 4 ].
What I would expect: [ 1, 4, 3, 2 ] [ 1, 2, 3, 4 ].
What I'm wondering, is why does this mutate the asdf variable? The bubbleSort function takes the given array (asdf), makes a copy of it (sort), and then deals with that variable and returns it, which asd is set equal to. I feel like an idiot but I have no clue why this is :(
No, it doesn't. Assignment doesn't make a copy of an object, it creates another reference to an existing object.
A simple way to copy an array is to use Array.prototype.slice:
For more on copying objects in general see: How do I correctly clone a JavaScript object?