# Need clarification about if-else statements

I’m pretty sure I am right about my question but just wanted to make sure and possibly gain any insight I may be missing.

In the following function:

``````function bubbleSort(array) {
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
bubbleSort(array)
}
}
return array
}
``````

If I set up an If–statement without an Else like I did in the function above, when will the function exit the loop and return?

It seems like when I put an If-statement without an Else, the loop doesn’t end when the If-statement evaluates to false. It just keeps moving onto the next iteration until the If-statement evaluates to true, and then it executes whatever is within the If-statement code-block.

So in regards to bubbleSort(array), the function only returns when the loop finishes iterating thru the array without the If-statement ever evaluating to true.

You can use console.log to print stuff to test things. press f12 in firefox to open console to see what is printed. one thing, you’ll see some undefined with the below code. that’s because i+1 sometimes goes beyond array length so change to array.length-1. man pasting code here messes up my indentation

``````function bubbleSort(array) {
for (let i = 0 ; i < array.length; i++){
console.log(array[i],array[i+1])
if (array[i] > array[i+1]){
let temp = array[i]
array[i] = array[i+1]
array[i+1] = temp
bubbleSort(array)
}
}
console.log('i\'m at this line now')
return array
}

ret=bubbleSort([6,7,3,9,8,1])
console.log(ret)``````

I never use nested recusion functions myself (function calls itself). They seem unnecessarily confusing. Here’s how I did it without recursion. Really though when it comes to sorting which needs to be fast, I’d look for a built in solution or search engine a fast solution instead of making one, but it’s good practice.

``````function bubblesort2(array){
while(1){
sorted=true
for(i=0;i<array.length-1;i++){
if(array[i]>array[i+1]){
sorted=false
temp=array[i]
array[i]=array[i+1]
array[i+1]=temp
}
}
if(sorted) break
}
}

a=[6,7,3,9,8,1]
bubblesort2(a)
console.log(a)
//didnt need 2 return anything since an array function parameter is a reference to the original``````