Refactor Global Variables Out of Functions - Difference between various Return statements

Tell us what’s happening:
Can anyone explain what is the difference between :

return arr.push(bookName);  // Variant1

and

arr.push(bookName);  //Variant 2
return arr;

My code passes if I use Variant 2 but I can’t understand what is wrong in Variant 1.

Your code so far


// the global variable
var bookList = ["The Hound of the Baskervilles", "On The Electrodynamics of Moving Bodies", "Philosophiæ Naturalis Principia Mathematica", "Disquisitiones Arithmeticae"];

/* This function should add a book to the list and return the list */
// New parameters should come before the bookName one

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

/* This function should remove a book from the list and return the list */
// New parameters should come before the bookName one

// Add your code below this line
function remove (list, bookName) {
  let arr = [...list];
  if (arr.indexOf(bookName) >= 0) {
    arr.splice(arr.indexOf(bookName),1);
    return arr;
  }
    
    
    // Add your code above this line
    
}

var newBookList = add(bookList, 'A Brief History of Time');
var newerBookList = remove(bookList, 'On The Electrodynamics of Moving Bodies');
var newestBookList = remove(add(bookList, 'A Brief History of Time'), 'On The Electrodynamics of Moving Bodies');

console.log(bookList);

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) 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/functional-programming/use-the-map-method-to-extract-data-from-an-array

The push method actually has a return value which is the length of the array after the new item is added. So when you write return arr.push(bookName), you are returning that length value which is a number and not the array arr.

In the second example, you push the item to arr and then second line returns the array arr.

1 Like