So let's say we have an array of objects like this:
let cards = [
{
suit: 'spades',
"value": '10'
},
{
suit: 'hearts',
value: 'Q'
},
{
suit: 'clubs',
value: '5'
}
]
Now to shuffle it, I saw a function like this:
function shuffle(cards) {
for (let i = cards.length - 1; i > 0; i --) {
const newIndex = Math.floor(Math.random() * (i + 1));
const oldValue = cards[newIndex]; // cards[newIndex] is an object, and we're assigning its address to oldValue
cards[newIndex] = cards[i]; // Now we're changing cards[newIndex] address to an address of another object
// So the oldValue address we set one line higher should change too
// Yet it stays unchanged
}
}
The thing I don't understand is described in the comments of the code above.
I wanted to ask, why it behaves like this - isn't it a classical 'pass by reference' example? Why is the oldValue variable not changing after we change the address of the object passed to it?
You are assigning new value to cards[newIndex]
. The rule about reference is not valid here as now cards[newIndex]
points to something else only(different address in memory).
The original variable still exists at a different address. Hence oldValue
still points to the, well, old value.
If you would have made any modifications to cards[newIndex]
like:
cards[newIndex]['value'] = 9;
it would have reflected.