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.
Thanks!