# Need explanation of "Where do I belong" exercise

I need an explanation of Solution #1 of this problem.

function getIndexToIns(arr, num) {
arr.sort((a, b) => a - b);

for (let i = 0; i < arr.length; i++) {
if (arr[i] >= num)
return i;
}
return arr.length;
}

The part I don’t understand is why do we have 2 return statements. One inside the IF statement which returns i and one outside which returns arr.length. I thought if we have a return the function stops at the point doesn’t it? If not, then when we return “i” where does this value go?

Why is the solution to return “arr.length” ?

If for example we call:
getIndexToIns([10, 20, 30, 40, 50], 35)

I know the solution should be 3, the IF statement returns 3 but why do we need to return arr.length? and at what point does arr.length get changed to 3?
I am a beginner so if someone can break it down I would appreciate it!

``````  **Your browser information:**
``````

User Agent is: `Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.127 Safari/537.36`

Challenge: Where do I Belong

You are 100% correct. As soon as you reach a `return` statement the function is over and it returns the value in the statement.

I’m not exactly sure I understand this question, but the value of `i` is returned by the function, so whatever called the function in the first place will take that value and do whatever it wants with it.

If the `if` statement returns 3, would you ever reach the other `return` statement. You just said above that once a function returns it stops completely. So how can you reach the second `return` statement if you reach the first one?

What is the function doing? It returns the lowest index at which a value (second argument) should be inserted into an array (first argument) once it has been sorted. Do you understand what the `for` loop is doing in the function? If the `return` statement in the `for` loop is never reached, what does that mean? If the function is returning the length of the array, what does that mean?

Oh man get it, for some reason I was thinking BOTH return statements were supposed to run and I was confused, I am sorry I should have known better. So yeah the function Returns a value if the IF condition is True, otherwise the last Return statement runs… thanks for pointing out the obvious to me!

No need to apologize. We all get messed up about things that seem simple every once in a while.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.