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>
typeis not "u", "One", "Two", "Three" - it's only "u". if you havefunction fn(arg1, arg2) { // body }and you call it asfn("foo", "bar", "baz"),arg1will be"foo",arg2will be"baz", and the third parameter will not have a variable created for it, but will feature inarguments