Javascript Quick Tips - accessing function arguments as an array
I came across this one while studying the script.aculo.us source code. So credit goes to Thomas Fuchs for introducing me to this seldom used and rarely mentioned JavaScript built-in gem:
Arguments passed to a function are accessible from within the function through the arguments array.
Consider the following:
function sum() {
var sum = 0;
for (var i = 0; i < arguments.length; i++) sum += arguments[i];
return sum;
}
sum(7, 2); // returns 9
sum(1, 100, 13, 4); // returns 118
This really comes in handy when you wish to pass optional parameters to a function (notice how we provide a default value for the param as described here):
var citation = "JavaScript is the world's most misunderstood programming language.";
function truncate(str) {
var limit = arguments[ 1 ] || 20;
return str.substring(0, limit).replace(/\s+$/) + '...';
}
truncate(citation);
// returns "JavaScript is the wo..."
truncate(citation, 30);
// returns "JavaScript is the world's most..."
or a la script.aculo.us, by passing a hash of params:
function truncate(str) {
var options = arguments[ 1 ];
options.limit = options.limit || 20;
options.suffix = options.suffix || '...';
return str.substring(0, options.limit).replace(/\s+$/) + options.suffix;
}
truncate(citation, {limit: 10);
// returns "JavaScript..."
truncate(citation, {limit: 30, suffix: '... [read more]'});
// returns "JavaScript is the world's most... [read more]"
The citation, by the way, is the title of one of Douglas Crockford’s introductory essays to JavaScript.