Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Question regarding the fisher yates shuffle function in JavaScript

Hi guys, hope everyone has had a wonderful festive period.

I'm somewhat new to javaScript and im trying to really understand how functions work.

Ive been studying the fisher yates shuffle function and i think I now understand how it works. There is one thing i dont understand however.

My shuffle function is below.

const myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];

  const shuffle = (arr)=>{

  let newPos,
      temp,
      i;
  for (i = arr.length -1; i > 0; i--){
    newPos = Math.floor(Math.random() * (i +1));
    temp = arr[i];
    arr[i] = arr[newPos];
    arr[newPos] = temp;
  }
  return  arr;
}

const randomArray = shuffle(myArray);

console.log(randomArray);

The queston i have is regarding the newPos let variable.

When declaring it as arr[newPos] why do i have to use the parameter arr?

Why can't i just use

    arr[i] = newPos;
    newPos = temp;

Hope that makes sense.

Thanks, Jiten.

1 Answer

Steven Parker
Steven Parker
243,266 Points

This code is swapping two array elements, "newPos" is not the contents of either one, but it's the index value of one of them. So "arr]newPos]" represents the element located at that index just like "arr[i]" represents the other one.