7

I'm confused with Node.js function arguments object.

Suppose i have following code:

function x() {
  return arguments;
}

console.log(x(1, 2, 3));

In chrome developer tools it returns as an Array:

[1, 2, 3]

But i got different result in node.js:

{ '0': 1, '1': 2, '2': 3 }

How come?

0

3 Answers 3

7

You see different representation of an object which isn't array in Chrome neither in Node and in javascript in general.

If you want an array out of it, you do that:

var args = Array.prototype.slice.call(arguments, 0);
Sign up to request clarification or add additional context in comments.

1 Comment

This saved me doing work in node, where I assumed that arguments was an array. Silly js developer. Browsers are for kids. "intern-runner": { command: function(){ var cmdArgs = ""; var args = Array.prototype.slice.call(arguments, 0); if(args){ cmdArgs = args.join(" "); } return 'node node_modules/intern/bin/intern-runner config=app/intern-config ' + cmdArgs; } },
5

arguments is a magic variable that isn't actually an Array. It behaves like an Array, but it doesn't have all the functions that an Array has.

Other objects like this are NodeList for example.

3 Comments

Ok @Frits van Campen. I got it. I run this to check it's type: console.log(Object.prototype.toString.call(x())); Both return same result: [object Arguments]
Cool, I didn't know you could do that =)
very funny frits. LoL
2

console.log is not part of javascript, and not part of v8. Which is why both chrome and node.js have there own implementations of console.log. They have simular apis, but not the same. The documentation for node's console.log is here: http://nodejs.org/api/stdio.html

Comments