Search code examples
javascriptreplit

Get code to not return undefined after running


I created a function that inserts a number into an array of integers. I am assuming that the array is always sorted already.I want it to return the lowest index where the number can be inserted. I have accomplished that but after it returns the index it also returns undefined when i run it on repl.it. Wondering why that is happening?

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


    console.log(lowestIndexInsert(32,[8,9,15,30,35]));


Solution

  • If the console.log() statement is part of your source code, you will just get the result you want. But, if you are actually executing the console.log() from a console, you will get the extra undefined because in a console, you don't have to ask for console.log(), which, itself has no return value (undefined). In that case, you would just invoke your function and let its return value be returned.