Record Collection - Why return?

Tell us what’s happening:
I just wanted to ask, since “collection” is a global variable and we mutate it, why should we return it inside the function?
Thank you.

Your code so far


// Setup
var collection = {
    "2548": {
      "album": "Slippery When Wet",
      "artist": "Bon Jovi",
      "tracks": [ 
        "Let It Rock", 
        "You Give Love a Bad Name" 
      ]
    },
    "2468": {
      "album": "1999",
      "artist": "Prince",
      "tracks": [ 
        "1999", 
        "Little Red Corvette" 
      ]
    },
    "1245": {
      "artist": "Robert Palmer",
      "tracks": [ ]
    },
    "5439": {
      "album": "ABBA Gold"
    }
};
// Keep a copy of the collection for tests
var collectionCopy = JSON.parse(JSON.stringify(collection));

// Only change code below this line
function updateRecords(id, prop, value) {
  if (prop!="tracks" && value!=""){
    collection[id][prop]=value
  }
  
  return collection;
}

Two things are going on.

  1. Global variables are being used to keep things simple for the beginner.
  2. Returning a value that you don’t technically need to from a function that exerts side effects or performs changes on parameters in situ is useful because it allows function chaining. A good example is Array.sort(), which can be used like this:
let myArray = ["the", "dogs", "barked"];
const newArray = myArray.sort().filter(word => word.length > 3);
console.log(newArray); //expected output: ['barked', 'dogs']
console.log(myArray); //expected output: ['barked', 'dogs', 'the'] 

Note that the original array is being altered, even though the array being returned from myArray.sort has filter applied to it, creating a new array that gets stored in newArray.

1 Like

In a pure sense, you always return something from a function. So says the MDN, and I’m not gonna argue with them. If you don’t specify a return value, then it returns undefined, but it will always return something.

Even if that something is… nothing.

1 Like