Hey guys, quick question about the push function that has my head spinning

Hey guys, quick question about the push function that has my head spinning
0

#1

If I have the function:

function getIndexToIns(arr, num) {
arr.push(num);
return arr;
}
getIndexToIns([40, 60], 50);

Then I will return ([40,60],50); which is dope.

But why is it when I do this:

function getIndexToIns(arr, num) {
var b = arr.push(num);
return b;
}
getIndexToIns([40, 60], 50);

I instead return 3? Shouldn’t making the arr.push(num); equal to a variable and then returning the variable give me the same result as the first function. So confused…


#2

.push changes the array with which it was called, but it also returns the new length of the array after adding a new element. The second example returned 3 because it’s the length of arr after you did a push.


#3
function pushToArray(arr, valueToAdd) {
    arr[arr.length] = valueToAdd;
    return arr.length; // what is returned when push() is called
    // return arr; // what you'd expect to happen, but does not happen
};

var b  = pushToArray([40, 60], 50);
console.log(b); // 3