Question about scope and do-while loops

How come in the following function, the variable ‘swapped’ is undefined :

function bubbleSort(array) {
    do {
      let swapped = false
      for (let i = 0; i < array.length; i++){
        if (array[i] > array[i+1]){
          let temp = array[i]
          array[i] = array[i+1]
          array[i+1] = temp 
          swapped = true 
    } while (swapped === true)
    return array 

However, when I declare ‘swapped’ before the do-block, the function works. Is it because when I declare ‘swapped’ within the do-block, it is only available to the do-block’s scope and therefore the while-statement cannot access it unless it is within the function’s global scope outside the do-block?

I know the answer has something to do with the scope here but I’m not very familiar with do-while loops and just need some clarification.


1 Like

You exactly solve it yourself. It is good when we are smarter than we think we are.

1 Like