If you hard code that your function is only going to use the global variable, then you cannot use any other data inside of the function. We want flexible functions.
Which parameter did I ignore? So your saying that the recordCollection is the global variable, and if I use it within my function again, it cant be used outside of my function? So i should use my parametersā¦?
Imagine you have two record collections on your computer, one for pop and one for punk. Those two are global variables, so you want to make sure that your function only works on the collection that you pass in as parameter. The function does its stuff and returns the updated collection. The other collection remains untouched.
I see, but how does the function know which record to access? Your saying by the parameter? How does the parameter know which word its referring to? Like dont you need to declare that as a variable or something? Sorry, I am quite new to programming.
So you have two collections, and one function to update either of those collections.
var collectionPop = {
1234: {
artist: 'Jon Bohn Jovi',
...
}
}
var collectionPunk = {
2345: {
artist: 'Angelic Upstarts',
...
}
}
// this updates only the pop collection
updateRecords(collectionPop, 1234, 'tracks', '1999')
// this updates only the punk collection
updateRecords(collectionPunk, 2345, 'tracks', 'Police Oppression')
The idea of a (reuseable) function is that you
give it some input
the function does stuff to the input (and only to the input, not something that exists outside of it)
the function returns some output
Note how inside the function, youāre never manipulating var recordCollection directly, you only manipulate the argument records that was passed in.
Donāt worry if you donāt get it right away, itāll sink in as you proceed.
That actually helped a lot, thank you. So by adding collectionPop as a parameter in that example, does that allow it to be reused even outside the function? Or notā¦?
and are all the parameters in the same function somehow linked to one another, like as in a particular order from left to right
The collection objects arenāt reusable, they always hold the current state of your collection data. When you update a collection, you reassign the variables collectionPop or collectionPunk to new values, so those variables now hold the updated collection.
var collectionPop = {...}
var collectionPunk = {...}
// now you update your pop collection
var collectionPop = updateRecords(collectionPop, 3456, ..., ...)
The function returns a new collection object. This new object is now stored in collectionPop, it has replaced the old object that was stored there before.
The word āresusableā means that your function works for both collection. You could have hundreds of collections, but you only need one function to update any of them. The function knows which collection to update, because you pass it in:
updateRecords(collectionPop, 3456, ..., ...)
All other collections remain completely untouched.