Reputation: 367
Why do we use [].join()
in this way?
function printArgs() {
arguments.join = [].join;
var argStr = arguments.join(':');
alert( argStr );
}
printArgs(1, 2, 3);
Upvotes: 4
Views: 87
Reputation: 1378
Because arguments
object is Array-like object but it is not real array and it doesn't have array properties (like join
in your example) except .length
. So in your code you are copying .join
method from array to arguments object.
Upvotes: 4
Reputation: 50291
The argument
object is an local variable array like object
which is available in all functions.
So arguments.join = [].join;
is creating a new array and on which you can use all methods that are available in js array.
Therefore var argStr = arguments.join(':');
will return 1:2:3
var argStr = arguments.join(); // assigns '1,2,3' to argStr
var argStr = arguments.join(' + '); // assigns '1 + 2 + 3' to argStr
// ^ ^ Note empty space here & in assigned value
var argStr = arguments.join(''); // assigns 123 to argStr
Upvotes: 0