Hello,
I just completed the “Build a Library” project in the Javascript III module. There, they challenge you to write a method that will shuffle the songs on a CD.
Instead of reinventing the wheel, I looked up this shuffling method from StackOverflow. I understand most of it, but I’d like to understand it better.
function shuffle(array) {
let currentIndex = array.length, randomIndex;
// While there remain elements to shuffle.
while (currentIndex != 0) {
// Pick a remaining element.
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex--;
// And swap it with the current element.
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
}
return array;
}
First, I’m unfamiliar with this syntax:
let currentIndex = array.length, randomIndex;
What does it mean when you let a variable equal two different values? Is this simply creating both values at once? If so, isn’t it more common to put them both on the left side of the equal sign?
Simlarly, I’m a little confused by the
[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];
It seems like we’re taking two variables (two indexes of the array) and setting them equal to two values, respectively. Is that correct?
Thanks in advance. Cheers!
-Z