Where do I Belong,

Tell us what’s happening:

Your code so far
Hi. I have tested this code on my browser, on https://ronakshah.net/console/ and result is Ok, but on freeCodeCamp I get “TypeError: unknown: Cannot read property ‘0’ of undefined”.
What is the matter?
Please, who can explain me.


function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
arr1 = arr.concat(num);
arr2 = arr1.sort((x,y)=>x-y);
for(var i = 0; i<arr2.length; i++)
if(arr2[i]===num)
return i;
}

getIndexToIns([40, 60], 50);

Your browser information:

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

Link to the challenge:

freeCodeCamp uses strict JavaScript rules. You are using variables without declaring them.

Overall your logic works, but you need to define the variables in the beginning.

var arr1 = arr.concat(num);
var arr2 = arr1.sort((x,y)=>x-y);

Also, I don’t see that you blocked out the other sections for the for loop and the if statement.

Your code is fine you just missed a few things:

On your for loop you need to put the {} at the end of it and pass the if statement in there. I would just put the return on the same line as the if statement as well. You also need to define arr1 and arr2.

I got it to pass like this

function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  let arr1 = arr.concat(num); //Define this variable
  let arr2 = arr1.sort((x,y)=>x-y); //This one too

  for(var i = 0; i<arr2.length; i++){   //<-Don't forget the curly braces
    if(arr2[i]===num) return i         //Pass the if statement inside the curly braces of the for loop
  }
}

getIndexToIns([40, 60], 50);

OK, This one is working!

function getIndexToIns(arr, num) {
// Find my place in this sorted array.
var arr1 = arr.concat(num);
var arr2 = arr1.sort((x,y)=>x-y);
for(var i = 0; i<arr2.length; i++){
if(arr2[i]===num)
return i;
}
return arr2.length;
}
getIndexToIns([40, 60], 50);