Reputation: 21425
I was asked this question in an interview on NodeJS,
What are the properties supported by arguments object.
a) caller
b) callee
c) length
d) All
When I googled then I found that all the 3 properties are present for an argument object.
But if I try to test this with a sample program I see that only Length property is present.
Here is my sample program:
var events = 'HelloWorld'
abc(events);
function abc(args) {
console.log(args.charAt(1))
console.log(args.callee);
console.log(args.caller);
console.log(args.length);
}
Here is the output:
e
undefined
undefined
10
So based on above output only length is the valid property, but based on above all 3 are valid properties. So what is the correct answer for this?
Upvotes: 2
Views: 793
Reputation: 7521
Your scoped variable args
and the local variable Function.arguments
are two very different things. In your function abc(args)
, args
is the scoped variable that will be whatever you pass into its invocation.
arguments
, however, is a local array-like variable that is accessible inside each function call, and corresponds with the values passed into a function. For example:
function foo(args) {
console.log(args);
console.log(arguments[0]);
console.log(arguments[1]);
console.log(arguments[2]);
}
foo("bar", "baz", 123, 456);
This will output:
> "bar"
> "bar"
> "baz"
> 123
Even though this function only takes one argument, args
, the local variable arguments
is still present, and it represents all arguments passed into this function. That way we can still find the value of the second, third, and fourth arguments even though they weren't declared as part of the function's scope.
The issue you're seeing is that you are trying to access properties of Function.arguments
in your scoped variable args
, when the two are simply different variables altogether. If you want to access those properties, reference arguments
instead:
var events = 'HelloWorld'
abc(events);
function abc(args) {
console.log(args.charAt(1));
console.log(arguments.callee);
// console.log(arguments.caller); //DEPRECATED
console.log(arguments.length);
}
Upvotes: 5