Background
I am learning how the arguments
object works inside a function. I noticed that in theory, this object will have all the arguments passed to the function.
In practice I have quite different results.
Code
The following code is a test function, that prints the arguments it receives:
function test(myArgs){
console.log(`myArgs: ${myArgs}`);
console.log(`arguments obj: ${JSON.stringify(arguments)}`);
console.log(`arguments array ${JSON.stringify(Array.from(arguments))}`);
}
the first line prints myArgs
and the other two print the arguments
object in a couple different ways.
Executing the function with something simple it works:
test("hello", 56, 60, 5);
myArgs: hello
arguments obj: {"0":"hello","1":56,"2":60,"3":5}
arguments array ["hello",56,60,5]
Problem
The problem comes when I pass a function as one of the arguments, like, lets say, a callback:
test("hello", () => console.log("HelloWorld"), 60, 5);
myArgs: hello
arguments obj: {"0":"hello","2":60,"3":5}
arguments array ["hello",null,60,5]
This is quite unexpected ...
Code
Following is a snippet that exemplifies this behavior:
function test(myArgs){
console.log(`myArgs: ${myArgs}`);
console.log(`arguments obj: ${JSON.stringify(arguments)}`);
console.log(`arguments array ${JSON.stringify(Array.from(arguments))}`);
}
test("hello", 56, 60, 5);
test("hello", () => console.log("HelloWorld"), 60, 5);
Questions
- Why doesn't this work?
- How can I access a function if I have multiple arguments ?