Add Items to an Array with push() and unshift(): Why can't I chain it?

Tell us what’s happening:
Hello, I just wanted to know why it doesn’t work when I chain unshift & push.
I figured the solution but I just wanted to know why I couldn’t just chain the code together.

Thank you :slight_smile:

Your code so far


function mixedNumbers(arr) {
  // change code below this line
  arr.unshift('I', 2, 'three').push(7, 'VIII', 9);
  // change code above this line
  return arr;
}

// do not change code below this line
console.log(mixedNumbers(['IV', 5, 'six']));

Your browser information:

User Agent is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-data-structures/add-items-to-an-array-with-push-and-unshift

Take a look at the return value of Array.push() – it doesn’t return the array object, it returns a numeric value, representing the length of the array.

Unshift does the same.

In order to “chain” a function, it needs to return the value you expect – so if Array.push() returned the array itself, you could. That’s why you can do Array.map().filter() – because the map() returns an array object, as does filter().

3 Likes

Thanks for this! :+1:

It’s not an easy read, but when you take the time to pore through the “official” js docs (those at Mozilla, for example), be careful to look not only at what it DOES, but what it RETURNS. It isn’t always what you expect, but it usually makes some sort of sense. :wink: