Reputation: 79
When I define a function why might I want to use a argument / parameter? What are the benefits of using arguments? How are they useful? Could somebody explain? Thanks.
var playList = [
'I Did It My Way',
'Respect',
'Imagine',
'Born to Run',
'Louie Louie',
'Maybellene'
];
function print(message) {
document.write(message);
}
function printList (list) {
var listHTML = '<ol>';
for (var i = 0; i < list.length; i += 1) {
listHTML += '<li>' + list[i] + '</li>';
}
listHTML += '</ol>';
print(listHTML);
}
printList(playList);
Why have arguments been used in the example above?
Upvotes: 2
Views: 1476
Reputation: 1809
The data in your example is hard-coded. This means that it is directly written into the code and in theory you could access it directly or hardcode it into method, but that would restrict it's reuseability.
In general you want to be able to read the data from a database, server or from userinput. That means that you need a way to pass the data into a function and assure that the data is always there when the function is called.
It also means you can reuse a function for different datasets if necessary, even if those sets were hard-coded.
Upvotes: 1
Reputation: 66364
Arguments let you apply the same logic to different data, meaning you can re-use code.
If you don't use arguments then there is a limitation on the re-usability of functions or methods, they can only really produce the same output repeatedly, the same as how asking a question over and over again with no new information will always give you the same answer.
In your example, the printList
function is written such that, if you wanted, you could generate multiple outputs by invoking it multiple times with different list
Arrays, rather than only being able to generate a single output based on the Array called playlist
The print
function is just a wrapper for document.write
. There are many reasons against using document.write
but you can worry about that after you've had some practice writing code.
Upvotes: 1