Reputation: 17574
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.
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]
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 ...
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);
Upvotes: 0
Views: 120
Reputation: 41665
By default, JSON.stringify()
doesn't serialize functions.
... but it can. Provide a custom replacer
callback and handle serialization of functions yourself:
var values = [1, false, {foo:2}, function bar() {}];
console.log(JSON.stringify(values, function(key, value) {
if ("function" === typeof value) {
return value.toString();
}
return value;
}));
See Function.prototype.toString()
and JSON.stringify(value, replacer)
.
Upvotes: 3