I am confused about how return works in the solution to the Basic Algorithm Scripting challenge - Where do I belong

Here is my solution to the problem - where do i belong


There are two things that confuse me about this question:

  1. What purpose does the return arr.length serve? I thought this would just return the length of the original array. Why doesn’t return arr.indexOf(i); work here instead?

  2. If you place the return array.length inside the loop you get different results. I understand that placing the return outside the loop will only return once the loop has finished iterating. How is the arr.length bringing back the correct answer, I thought having the loop break once it found the correct index would be the right call instead, hence putting the return inside the loop.

Hi @dan_friend !

Welcome to the forum!

I added spoiler tags around your code since it is a full working solution.

It is always best to write code directly into the forum instead of posting screenshots.

When you enter a code block into a forum post, please precede it with a separate line of three backticks and follow it with a separate line of three backticks to make it easier to read.

You can also use the “preformatted text” tool in the editor (</>) to add backticks around text.

See this post to find the backtick on your keyboard.
Note: Backticks (`) are not single quotes (’).


Hey thanks for the welcome and the reply!

Sorry, in future I will put my code in like you say!

what happens if arr[i] > num is always false? or if arr.length is 0?

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