Have you used console.log() method? Have you ever wondered what's the maximum number of parameters it takes? Answer is as many as it can.
Lets take an example.
function print(x,y){
console.log(x);
console.log(y);
}
Well this is an easy function, takes 2 arguments and print them in the console.
Lets say I have 5 parameters passed to function print. a,b,c,d,e. How would you modify the print method? May be something like this. (Don't write programs like this. It ain't effective).
function print(a,b,c,d,e){
console.log(a);
console.log(b);
console.log(c);
console.log(d);
console.log(e);
}
How about if I pass 100 parameters like, a1, a2, ... a100. What if I pass 1000 parameters. You can't write 1000 console.log statements to print them. So you would think of a for loop to print all the parameters.
But wait!
How do I access all the parameters inside a for loop unless if they are an array (use for-loop or for-in to iterate) or an object (use for-in to iterate)?
Now comes the object "arguments". This is a built-in object implicitly created by javascript for every function you declare.
What does this store? It stores all the parameters you passed to the function in the form of object.
arguments {
0: a,
1: b,
2: c,
3: d,
4: e
};
Now I have something like an object that holds all the parameters passed to the function, it will be easier to access them in a for-in loop. Now my print method will look like:
function print(a,b,c,d,e,f) {
for (var prop in arguments) {
console.log(arguments[prop]);
}
}
This will loop through all the properties of the arguments object and prints the value stored in each property.
What is stored in each property of argument object?
fn parameter object-property value stored in property
a 0 value of parameter a
b 1 value of parameter b
c 2 value of parameter c
d 3 value of parameter d
e 4 value of parameter e
f 5 value of parameter f