VARIADIC FUNCTIONS IN JAVASCRIPT
KERALA JS USER GROUP MEETUP - SEPT 2014
Variadic What?
In computer programming, a variadic function is a function of indefinite arity, i.e., one which accepts a variable number of arguments.
The best example!
#include <stdio.h>
int main(){
printf("Hello world!");
return 0;
}
#include <stdio.h>
int main(){
printf("Hello world! \n %d + %d = %d", 1, 2, 1+2);
return 0;
}
Function Arguments
var concat = function(arg) {
return arg;
}
concat();
//=> undefined
concat('Hi There!');
//=> 'Hi There!'
concat('Hi There', 'Hi There Again');
//=> 'Hi There!'
Arguments Object
The arguments object is an Array-like object corresponding to the arguments passed to a function.
- MDN JavaScript Reference
...
var whatAreTheParameters = function() {
return arguments;
}
whatAreTheParameters()
//=> []
whatAreTheParameters(1)
//=> [1]
whatAreTheParameters(1, 'two', 3.0)
//=> [1, 'two', 3]
Concat Function
var concat = function() {
var result = '';
for(var i=0; i < arguments.length; i++)
result += arguments[i];
return('' == result ? undefined : result);
}
concat('Hello ', 'world');
//=> 'Hello world!'
List Function
var list = function(type) {
var result = '<' + type + 'l><li>';
var args = Array.prototype.slice.call(arguments, 1);
result += args.join('</li><li>');
result += '</li></' + type + 'l>';
return result;
}
list('u', 'one', 'two');
//=> '<ul><li>one</li><li>two</li></ul>'
ECMAScript 6
Rest Parameters
var list = function(type, ...args) {
var result = '<' + type + 'l><li>';
result += args.join('</li><li>');
result += '</li></' + type + 'l>';
return result;
}
response.end('thanks!');
io.on('questions', function(q){
if(questions.indexOf(q) > 0)
io.emit('answers', answer(q));
});
Variadic Functions In Javascript
By akhil stanislavose
Variadic Functions In Javascript
- 2,420