Could I get assistance understanding this Syntax?

Hello, I was working on the project for the meal maker :

At the end of the project they said to test our knowledge and see if we could test an array into the codes we inputted. I wanted to see if I could do a randomized Array for the extra challenge and I came about a line of code for stack Overflow : How to randomize (shuffle) a JavaScript array? - Stack Overflow

However, I am having trouble understanding it.

The code reads as follows

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);

    // And swap it with the current element.
    [array[currentIndex], array[randomIndex]] = [
      array[randomIndex], array[currentIndex]];

  return array;

// Used like so
var arr = [2, 11, 37, 42];

So want to start with one thing at a time. First things first, what does this line mean  ? 

let currentIndex = array.length, randomIndex;

I am very thrown off by this. Am I assigning two values to currentIndex ? 

If so, am I giving the currentIndex the value of the length of the array ? 

If so, what exactly is the value of the randomIndex? 

Is randomIndex being assigned to currentIndex first, then having it's value reassigned on this line ? 

randomIndex = Math.floor(Math.random() * currentIndex);

Sorry for all the questions, I think if I get an understanding of this part it will really help me better grasp the rest of the code.

The above line is the equivalent of writing:

let currentIndex = array.length;
let randomIndex;

The last line declares a variable without defining it as a value hasn’t been set, yet. let and const (and var) permit multiple declarations in one statement:

let a = 1, b = 2, c = 3, d;

In a similar situation to the sample code, d doesn’t get defined until inside the loop, but it still has the function block scope let gives it.

Side note:

We cannot declare a constant without defining it, which makes sense since they cannot be reassigned.

 const a = 1, b = 2, c = 3;
 let d;

Thank you so much, what you said helped me understand that.

It always feels like it’s something simple that stops it from all coming together.

I wanted to ask for the second line of code

[array[currentIndex], array[randomIndex]] = [
array[randomIndex], array[currentIndex]];

return array;


This trips me up as well. I understand it is meant to be the swap formula for arrays, but I don’t fully grasp how it works.

1 Like

You’re welcome.

Go to MDN and read up on destructuring assignment.

1 Like