Making full use of the Arguments object
In Javascript, arguments are the variables passed to a function. We might think of a soda machine that accepts coins that are then processed, returning your favorite carbonated beverage. Likening this to a function, the coins are arguments.
In general these arguments are accessed by named variables as represented in the following example by str1 and str2:
return str1 + str2;
}
concatenateTwoStrings('foo', 'bar');
// returns 'foobar'
It's not always convenient however to access our arguments in named manner. As such, Javascript provides the Arguments object. This "Array-Like" object is accessed like this:
return arguments[0] + arguments[1];
}
concatenateTwoStrings('foo', 'bar');
// returns 'foobar'
The power of using the arguments object is evident when we're not sure how many arguments will be passed into our function. For instance, we might write a function that will concatenate an unknown amount of strings.
var result = '';
for(var i=0; i <arguments.length; ++i){
result += arguments[i];
}
return result;
}
concatenate('douglas', 'crockford', 'has', 'a', 'posse');
// returns 'douglascrocfordhasaposse'
Nice, right? Well, sort of. To actually concatenate a large amount of strings in this manner is very slow. In JavaScript, it's actually significant faster to first add each string to an array, and concatenate them using the array's join method.
var result = [];
for(var i=0; i <arguments.length; ++i){
result.push(arguments[i]);
}
return result.join('');
}
concatenate('douglas', 'crockford', 'has', 'a', 'posse');
// returns 'douglascrocfordhasaposse'
Now you might be thinking we could just us the join method on the arguments object. The problem is, though Arguments has a length property, it's technically not an Array. It's known as "Array-like." That said however, in JavaScript, the methods of an object are not restricted to be used only by itself. Javascript provides two amazing little methods, call and apply, that are properties of EVERY function, and will allow us to essentially hijack them from their parent, and use them as if our desired object was their parent.
Check this out:
return Array.prototype.slice.call(arguments).join('');
}
concatenate('douglas', 'crockford', 'has', 'a', 'posse');
// returns 'douglascrocfordhasaposse'
Now that's pretty obscure JavaScript but it's so so hot.
Now, to finish up here, we might want to provide ourselves a little flexibility in how we want each string concatenated. For instance, we might want a space or comma-separated string instead of everything simply merged together.
return Array.prototype.slice.call(arguments, 1).join(separator);
}
concatenate(' ', 'douglas', 'crockford', 'has', 'a', 'posse');
// returns 'douglas crockford has a posse'

1 Comment