2

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?

  • At here: https://www.quora.com/Is-it-a-bad-practice-to-access-the-arguments-object-to-every-function-that-takes-parameters, Varun Dua says that accessing the arguments object is 40% slower than if you use named parameters. I have not done such benchmark myself. FYI only. – Stack0verflow Aug 30 '15 at 17:03
  • How would you write those functions without parameters? – Bergi Aug 30 '15 at 17:30
  • @Bergi, in Javascript, there is such a thing called arguments, cref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/arguments – Stack0verflow Aug 30 '15 at 18:44
  • @Stack0verflow: I know, but that's not what the OP meant (and it still uses arguments in the calls) – Bergi Aug 30 '15 at 19:54

2 Answers2

1

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.

Community
  • 1
  • 1
Paul S.
  • 58,277
  • 8
  • 106
  • 120
1

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.

HopefullyHelpful
  • 1,529
  • 3
  • 17
  • 36