Where do I Belong testcase fail

Tell us what’s happening:
when null array is passes, it fails to retun 0, although it is specified.
if(arr.length===0)
return arr.length;

Your code so far


function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  arr.sort(function(a,b) { return a - b; });
  console.log(arr.length);
  for(var i = 0;i<arr.length;i++)
  {
    if(arr[i]<num && arr[i+1]>=num)
      return i+1;
     if(arr[arr.length-1]<num)
      return arr.length;
     if(arr[i]<=num && arr[i+1]>num)
      return i;
    if(arr.length===0)
    return arr.length;
  }
  return arr;
}
getIndexToIns([], 1);

Your browser information:

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

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/where-do-i-belong

I can’t debug your code now as I am not on computer, but you can remove the if statements that don’t have an i inside from the loop.

How can the if statement that execute for arr.length === 0 if in that case i can’t be less than 0 as it starts at 0? (Remember the condition of the loop, i < arr.length, the body loop is executed only if this is true, and 0 < 0 is false)

The other one about last element of the array is also not needed inside the array, as it doesn’t have a i inside, so you can move it above.

One of these statements can become first thing of the function , the other needs to be written after something else.

All of your if statements occur inside of a loop, but that loop only runs if i is less than the length of the array. When the array is empty, it’s length is 0. Since i is never less than arr.length the code inside of the for loop never runs, so your if(arr.length===0) will never be true.