6

I study the following code to log:

console.log.apply( console, arguments );

What is the purpose of apply() here?

Why not just console.log("message", arguments)?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ricky
  • 34,377
  • 39
  • 91
  • 131

3 Answers3

8
console.log("message", arguments)

calls log with two arguments, "message" and the array-like object arguments.

console.log.apply( console, arguments );

calls it with n arguments, where n is the length of the array-like object arguments. In other words, arguments is unwrapped into individual arguments. The context of the method is console. E.g.:

function foo(a, b, c)
{
  console.log.apply( console, arguments );
}
foo(1,2,3);

is roughly equivalent to:

console.log(1,2,3);
Matthew Flaschen
  • 278,309
  • 50
  • 514
  • 539
  • 1
    For compatibility with IE9 `console.log.apply(console, arguments);` may be changed to `Function.prototype.apply.call(console.log, console, arguments);` – Victor Oct 29 '13 at 09:56
7

The apply() function calls another function with a given this value and arguments provided as an array.

The reason for an implicit func.apply(obj, args) is to make sure that within func(), this refers to obj.

Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
0

I think both answers did not explain why. The real shiny use of this way to program.

I did not like the first voted answer. I could not understand it even reading thrice and the second one feels incomplete.

I think the main purpose to write this way is to use it inside a function (or closures).

So, this line only makes sense inside your customized logger: console.log.apply( console, arguments );

Probably it was a better approach than write to something like this:

function my_worse_way_to_log_dynamic_args ( [several dynamic arguments] )
{
    // loop each argument
    // call console.log for each one
}

function my_better_way_to_log_dynamic_args ( [several dynamic arguments] )
{
    console.log.apply( console, arguments );
}
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ismael
  • 2,330
  • 1
  • 25
  • 37