Question: Why doesn't this two codes do the same thing ?

Can someone explain to me where is the trick ?

```js
function randomize(arr){

    for(var i = 0; i < arr.length; i++){
        const random = Math.floor(Math.random()*arr.length);
        let temp = arr[i];   
        let newR = arr[random];
        [temp, newR] = [newR, temp];

    }
    return arr;
}

console.log(randomize([1,2,3,4,5]));
```

```js
function randomize(arr){

    for(var i = 0; i < arr.length; i++){
        const random = Math.floor(Math.random()*arr.length);

        [arr[i], arr[random]] = [arr[random], arr[i]];

    }
    return arr;
}

console.log(randomize([1,2,3,4,5]));
```

I am most grateful for your read !

Answer: 
With the following, you are swapping `temp` and `newR` however, the original array items stay intact and are not swapped. Hence, the output remains the same as input. 

```
 let temp = arr[i];   
 let newR = arr[random];
 [temp, newR] = [newR, temp];

```

With the later you are swapping the array items, hence, the array gets updated.

```
[arr[i], arr[random]] = [arr[random], arr[i]];

```
Because in JavaScript you cannot pass primitive values by reference, but only by value. Only compound values (Object, Array) can be assigned by reference.

```
let arr = ["one", 2, {name: "foo"}];

```

if you do

```
let item = arr[0];

```

then you are just copying it the value.
Changing `item` will not modify the value of `arr[i]`, because there is no reference to it.

But if you would do following

```
let obj = arr[2];

```

you would have a reference to the object at the 3rd position. 
you could reassign obj with something different, that would not change `arr[2]`. But if you access the `name` property and change it, you are changing a property of a referenced object. 

```
obj.name = "bar";
console.log(obj === arr[2]);
console.log(arr[2].name === "bar");

obj = "something else";
console.log(arr[2] !== obj);

```