Can anybody help me understand this syntax?

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

Hi,
For your first query, it’s shorthand for the two lines;
let currentIndex = array.length;
let randomIndex;
i.e initialising multiple variables on one line.
Though, there’s not really much benefit in writing it out this way. There’s no performance increase and, as you’ve noticed, it’s not as readable as giving each their own line.

The second one is swapping the values with each other.
Say you had [a, b] and wanted to swap them to [b, a].
Usually, you’d need use a temp variable;
i.e.
temp = b
b = a
a = temp
Using [a, b] = [b, a] does the same thing, but all the work is done in the background.

hope that helps

That makes a lot of sense. Thank you!

Do you know if the pattern on the second one can be used in similar ways that don’t involve direct swapping?

For example

[arr[2], arr[5]] = [arr[3], arr[6]]

Thanks again!