I must not understand how push works

I must not understand how push works
0

My question is related to: “Basic Algorithm Scripting: Where do I Belong”, but not really a question about the problem.

I was wondering why my code is returning a “3” instead of [40,60,50] or even [40,60],50. Why is it counting the length of arr and num?

My code.

function getIndexToIns(arr, num) {
  let newarr= arr.push(num)
  console.log(newarr)
  return newarr;
}
getIndexToIns([40, 60], 50);

Thanks in advance!

It just so happens push also returns a value when a new value is “pushed”. The value is the new length of the array. You are assigning the value 3 to newarr.

1 Like

.push() returns the length of the array.

If you want to return the array with the pushed value you should just return arr since it gets modified when you use .push().

1 Like

Thank you! That makes sense! Helped me understand the other response too!

1 Like