javascriptarguments-object

understanding basics of arguments in javascript


hey guys i am very new to java scripts but have read a few beginner books on js and i was going through the MDN doc's to understand how arguments works in js and came across the following script :

    function list(type) {
      var result = "<" + type + "l><li>";
      var args = Array.prototype.slice.call(arguments, 1);
      result += args.join("</li><li>");
      result += "</li></" + type + "l>"; // end list
    
      return result;
    }

    var listHTML = list("u", "One", "Two", "Three");

console.log(listHTML);  // "<ul><li>One</li><li>Two</li><li>Three</li></ul>"

have a close look at what gets printed out .

now this works quite counter intuitive to how i expected it to work .

so lets break it down , suppose i call the function list like below :

list("u", "One", "Two", "Three");

now what happens in the list function is

  var result = "<" + type + "l><li>"; // here type is still --  "u", "One", "Two", "Three" , than why does only u get inserted ?? 
  var args = Array.prototype.slice.call(arguments, 1); // in understand this line 
  result += args.join("</li><li>");
  result += "</li></" + type + "l>"; // end list

  return result;

for this programme to work as i figured out , it is critical that on the 1st line only "u" get inserted and not all the arguments (see my comment) , but how is this being done in this snippet , i know it a simple snippet of code , but i am really sitting here , scratching my head looking at this code.

can somebody explain ?

EDIT my expected output is :

<uOneTwoThreel><li>One</li><li>Two</li><li>Three</li></uOneTwoThreel>

Solution

  • In Javascript the pseudo-array arguments contains everything that has been passed to the function, while the named arguments listed in the function argument list get filled with the passed value ignoring extra arguments and setting undefined if not enough argument have been passed.

    For example calling function f(x, y){...} with f(1,2,3,4) will have

    and instead calling function g(x, y){...} with g(1) will have

    Note that arguments is not an array, and therefore you cannot use all array methods (like join). This is the reason for which the slice trick is used to convert all arguments skipping the first one in an array.