Why do I have to return the arr.length at the bottom of the function

this is a function to identify where a specific number belongs in an array I have looked into the solution and it has return arr.length at the end I tried to run my solution without that line but it did not work until I copied it and past it so why do I have to return the length of the array

[https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong](https://challenge link)

We really need to see your code in order to give you a good answer. You can paste it in here but remember you need to wrap it in triple backticks.

I’m assuming you are referring to Solution 1 in the hints? Remember, the function always needs to return the index of where the number should be inserted. If the number to be inserted is greater than all of the numbers in the array then where would you insert it?

Because the lengths of the array would be the index where you insert a new element that is larger than any other element in the array → which would cause all previous tests to fail.

1 Like
function getIndexToIns(arr, num) {

  arr.sort((a, b) => a - b);

  for (let i = 0; i < arr.length; i++) {

    if (arr[i] >= num) {

      return i

    }

  }

}

getIndexToIns([40, 60], 50);

You left out the triple backticks. Put three backticks on a line by themselves, then your code, then on a new line after your code three more backticks. On my keyboard the backtick is found in the upper left above the Tab key.

As for your code, I’ll ask again, what if the number passed into the function is greater than all of the numbers in the array? Where would you put that number? In other words, what index would you return?

3 Likes

I’ve edited your post for readability. 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 (’).

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