What are the benefits of using arguments in functions?

advertisements

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?


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.