Where do I belong? My Code works but I am confused

Where do I belong? My Code works but I am confused
0

#1

The following code for the “Where do I belong” challenge works:

function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  arr.push(num);
  arr.sort(function(a,b){return a-b;});
  return arr.indexOf(num);
  
}

However, when I string the functions in a chain like so:

function getIndexToIns(arr, num) {
  // Find my place in this sorted array.
  return arr.push(num).sort(function(a,b){return a-b;}).indexOf(num);
  
  
}

The error I get is arr.push(…).sort is not a function.


#2

Whenever you call a function, it will be evaluated. So before you chain functions together you need to know what they evaluate to, what they return.
Here is the documentation for “array.push”: https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/push

You can read it in there what this function returns:
“Return value: The new length property of the object upon which the method was called.”

So, the function push returns the length of the new array. If you had the following array:
let array = ["a","b","c"]
and you did array.push("d"), this call to “push” will evaluate to “4”, because that’s the length of the new array, and what the function “push” returns, you see?

So what you’re doing with arr.push evaluates to a number. Arr.push(num) is equal to the length of Arr, not to Arr itself.
Arr.push(num).sort() is equal to Arr.length.sort(), not Arr.sort()

When in doubt, just type in console.log(arr.push(num)), that will show you what arr.push turns into and if that is really what you wanted to write.