Where do I belong | Basic algorithm challenges

I managed to solve this but I’m not sure about the quality of my code especially since there is no closing else{} statement. Is the below snippet legitimate Javascript or not? Many thanks.

function getIndexToIns(arr, num) {

  var sortedArray = arr.sort(function(a,b){return a-b;}),
  lastNumber = arr[arr.length-1];

 for(var i=0;i<arr.length;i++){
    return arr.length;
  }else if(num>arr[i]&&num<arr[i+1]){
    return arr.indexOf(arr[i+1]);
  }else if(num==arr[i]&&num<arr[i+1]){
    return arr.indexOf(arr[i]);

It’s “legitimate” sure, but good instinct on being a little uncomfortable with the way it exits. It’s good practice to make sure that a function that is expected to return always returns something. Ideally this would be some value that makes it clear that the function wasn’t able to do what you want it to. For example: in this case your function is supposed to return an integer representing an array index so you could return -1 as a fallthrough because this is an invalid index value (like how indexOf returns -1 if the item is not found).

In this solution, I might do something like

function getIndexToIns(arr, num) )
    else if 
    console.log("Failed to find correct index for " + num);
    return -1;
1 Like

Thanks very much!! Good thing to keep in mind and to make sure my code is on the safe side.:slight_smile: