Accepting n Arguments


© Muhammad Ali Shah

  • Level: Intermediate
  • Skills Required: Function and Argument Concepts

Variable number of arguments seem to be facinating. In almost all high level languages (include Java, C++ and Pascal), the programmers are given a function to write something to console (the screen). Usually, this function can accept any number of arguments and is named something like print or write. There are situations when you want the same functionality from JavaScript.

We will write a function that accepts n arguments and show them with the help of an alert box. Within any function, you can get the number of arguments sent to it by arguments.length and the value of each argument by arguments[i]. Consider the following code:


<script language="JavaScript1.2">
function showArguments ()
{
   var str = "";
   var n = arguments.length;

   for (i=0; i<n; i++)
      str += arguments[i] + "\n";
   alert (str);
}

showArguments ('Akbar Ali', 'Muhammad Ali', 'Hassan Ali', 'Ahsan Ali');
</script>

The above JavaScript code defines the function showArguments(). Note that it doesn't accept any parameter explictly. Next it is called with four arguments. The function internally stores the number of arguments in variable n and uses a for loop to get the values of individual arguments. The results are stored in a string and then shown with the help of an alert box.

Go To Page: 1


The copyright of the article Accepting n Arguments in JavaScript is owned by . Permission to republish Accepting n Arguments in print or online must be granted by the author in writing.

Post this Article to facebook Add this Article to del.icio.us! Digg this Article furl this Article Add this Article to Reddit Add this Article to Technorati Add this Article to Newsvine Add this Article to Windows Live Add this Article to Yahoo Add this Article to StumbleUpon Add this Article to BlinkLists Add this Article to Spurl Add this Article to Google Add this Article to Ask Add this Article to Squidoo