A question on Bubble Sort Method in Number Sorter Course

Hi everyone! When I was taking the Number Sorter course, I have a question on the Bubble Sort method.

The code:

const bubbleSort = (array) => {
  for (let i = 0; i < array.length; i++) {
    for (let j = 0; j < array.length - 1; j++) {
      if (array[j] > array[j + 1]) {
        const temp = array[j];
        array[j] = array[j + 1];
        array[j + 1] = temp;
      }
    }
  }
  return array;
}

For this part:

        const temp = array[j];
        array[j] = array[j + 1];
        array[j + 1] = temp;

I know that it is used to switch the position of the numbers.
However, since array[j] = array[j + 1]; , wouldn’t const temp become array[j+1]?
I’m just a bit confused at how the switching of position works, since adding three equations seems to result in temp = array[j] = array[j+1] (i.e. all three are the same).

Thanks for your help! :slightly_smiling_face:

temp = array[j] = array[j+1] would mean that everything is the same, but code is executed line by line:

        const temp = array[j];
  • temp and array[j] point to the same value (lets call it X)
        array[j] = array[j + 1]; 
  • array[j] and array[j + 1] point to the same value (lets call it Y)
  • At this point only temp points to the X
        array[j + 1] = temp;
  • array[j + 1] and temp point to the X
  • array[j] points to the Y

@sanity Oh I see. What would happen if the word “const” is missing?

It could have been let, it could have been var, or nothing, for the example all would be the same.

Specifically, in the freeCodeCamp editor, when variable wouldn’t be declared, code would not work. It runs in a strict mode and requires all variables to be declared.