0

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?

PRMK
  • 15
  • 4
  • 1
    Your `shuffle` is wrong. You move an item but you don't save the previous item first. So if you move index `2` to `0` you now have two copies of whatever item was at index `2`. That would be the case even if you had an array of primitives like `["a", "b", "c"]`. See [How to randomize (shuffle) a JavaScript array?](https://stackoverflow.com/q/2450954) for proper implementations. – VLAZ Jun 29 '21 at 16:02
  • think of it this way ... if you did `let X = cards[1]; x= cards[2]` - would you expect `cards[1]` would change? – Jaromanda X Jun 29 '21 at 16:16
  • I know, that it's missing a line. I just wanted to understand the issue I described. – PRMK Jun 29 '21 at 16:54

1 Answers1

1

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.

Tushar Shahi
  • 16,452
  • 1
  • 18
  • 39