Difference between return arr.push(x) and arr.push(x); return arr

Tell us what’s happening:
On the challenge: https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/refactor-global-variables-out-of-functions

There is this function I wrote. This works…

function add (arr, bookName) {
  let listOfBooks = [...arr];
  listOfBooks.push(bookName);
  return listOfBooks;
  
  // Add your code above this line
}

but previously I wrote:

return listOfBooks.push(bookName);

and that wasnt working.
I did not understand the difference between the two.
Could anyone help me with that?

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:63.0) Gecko/20100101 Firefox/63.0.

**Link to the challenge:**https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/functional-programming/refactor-global-variables-out-of-functions

one returns the value of arr and the other just pushes a value to arr (which doesnt need return)

1 Like

I think when you write return listOfBooks.push(bookName); it returns the item that was pushed.
and when you write return listOfBooks; it returns the whole array with the new item pushed.

1 Like

Difference between return arr.push(x) and arr.push(x); return arr

Array.push is a mutating function which will insert a new element into the array. this function will return the length property of the new array as refered by the doc:

so

let arr = ["a","b"]
return arr.push("c") // will return 3

while

let arr = ["a","b"]
arr.push("c")
return arr // will return the array ["a","b","c"]
1 Like

Thank you for the example and reference. I appreciate.