'What is the purpose of JavaScript's apply() in this case?

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)?



Solution 1:[1]

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);

Solution 2:[2]

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 );
}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Peter Mortensen