Flame_Phoenix
Flame_Phoenix

Reputation: 17574

JavaScript arguments object does not have all parameters

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

  1. Why doesn't this work?
  2. How can I access a function if I have multiple arguments ?

Upvotes: 0

Views: 120

Answers (1)

canon
canon

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

Related Questions