Learn how does the arguments reserved keyword works in functions.

The arguments object is an Array-like object corresponding to the arguments passed to a function. You can use this for handle recursive functions parameters.To determine the number of parameters in the function signature, use the length property.

Analyze the following example, the JoinStringsInFunctions will return a string composed by all the given strings in every parameter :

// Note that the function doesn't expect any argument yet !
function JoinStringsInFunctions() {
  var receivedArguments = Array.prototype.slice.call(arguments, 0);// This will make the arguments as an array and will include all the items on it
  return receivedArguments.join("-");
}

// Then execute
var finalText = JoinStringsInFunctions("Hello","From","Our Code World");

console.log(finalText); // Output : "Hello-From-Our Code World"

Obviously is a really simple function and we need to check for types (to join only strings) etc.  But if the function expects parameters then you need to change the index of slice function :

function JoinStringsInFunctions(separator) {
  // change the 0 to 1 to expect the first parameter
  var receivedArguments = Array.prototype.slice.call(arguments, 1);
  return receivedArguments.join(separator);
}

// Then execute
var mySeparator = "< - >";
var finalText = JoinStringsInFunctions(mySeparator,"Hello","From","Our Code World");

console.log(finalText); // Output: "Hello< - >From< - >Our Code World"

Creating a html list

We are going to create a html list with all the received parameters, but we expect the type of list in the first parameter (ul or ol), therefore :

function CreateList(listType){
  var args = Array.prototype.slice.call(arguments, 1);// Expects the first parameter
  var html = "<"+listType+">";

  for(var i = 0;i < args.length;i++){
      var item = args[i];
      html += '<li>'+item+'</li>';
  }
   
  html += "</"+listType+">";
  return html;
}

CreateList("ul","Hello","From","Our","Code","World");

// Outputs : <ul><li>Hello</li><li>From</li><li>Our</li><li>Code</li><li>World</li></ul>

Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors