Build a Library project

Hi!
I have a question regarding Build a Library project.
Task 25, where you are asked to randomize songs on your CD.
I found this code:

    for(let i = this.songs.length - 1; i > 0; i--){
  		const j = Math.floor(Math.random() * i);
  		const temp = this.songs[i];
  		this.songs[i] = this.songs[j];
  		this.songs[j] = temp;
		}
  }

and it works, but I don’t get this bit

const temp = this.songs[i];
  	this.songs[i] = this.songs[j];
  	this.songs[j] = temp;

Can somebody explain why can’t I just put it like this?:

  	this.songs[i] = this.songs[j];

and instead have to create another variable and make extra moves.

Because you don’t want to lose songs.

Here you switch the songs position.

const temp = this.songs[i];
  	this.songs[i] = this.songs[j];
  	this.songs[j] = temp;

Whilst here you overwrite i with a duplicate of the song at index j.

this.songs[i] = this.songs[j];
1 Like

The last line

	this.songs[j] = temp;

means literally

	this.songs[j] = this.songs[i];

since

temp = this.songs[i];

So can’t I just write this?:

this.songs[j] = this.songs[i];

Trying to do this in one step won’t work, you need to temporary store the value in a variable (step 1), so you still have the value you have overwritten in step 2 (given its stored in the temporary variable).

what you attempt to do here is a swap, in general terms, if you have x and y, you want to assign the value of x to y, and the value of y to x. Trying to do this in one step won’t work, given then you can’t to the opposite assignment anymore given the original value in x is overwritten.

1 Like

I finally got it. But only after putting console.log inside the loop:

var songs = [111, 222, 333, 444, 555];
for(let i = songs.length - 1; i > 0; i--){
      const j = Math.floor(Math.random() * i);
      const temp = songs[i];
      songs[i] = songs[j];
      songs[j] = tstrong textemp;
      console.log(songs);
    }

This is literally what I meant by my post :stuck_out_tongue: Only you described it in more words.

This topic was automatically closed 60 minutes after the last reply. New replies are no longer allowed.

more words can sometimes help :wink:

1 Like