Thursday 30 May 2013

Named Parameters in JavaScript

JavaScript does not support Named Parameters, but given how malleable the language is, there should be some way to achieve something similar (bearing in mind that eval and function.toString are so powerful functions that should make any C#/Java guy with an interest in Reflection cry with envy).
I got interested on this idea after glancing over this article that mentions that Angular.js sort of implements it.

Named parametes are mainly useful for functions with a long list of parameters, and the normal way to address this in javascript is using an options object (like for example $.ajax does). I mean:

//rather than: 
function sayHi(name, age, city, language){
...

//use
function sayHi(options){
...

//and invoke it like this:
sayHi({
 city: "Prague", 
 age: 20,
 name: "Iyan"
 });

the above solution seems good to me, but has 2 problems:

  • Now the code in your function will be like this: options.name, options.age... rather than name, age...
  • What if you already have an existing function and want to enable named parameters in it?

Well, that's just what I've done. I've written a simple function enableNamedParameters that will receive a function and will return a new one that can be invoked with a "NamedParameters" object, or with a normal parameters list as in the original function.

Usage is like this:

function sayHi(name, age, city, language){
 console.log("hi, my name is: " + name 
 + " my age is: " + age
 + " I live in: " + city
 + " and my native language is: " + language);
}

var sayHi2 = enableNamedParameters(sayHi);

//using named parameters
sayHi2(NamedParameters({
 city: "Prague", 
 age: 20,
 name: "Iyan"
 }
));

//using no named parameters
sayHi2("Iyan", 20, "Prague", "English");

sayHi2("Iyan");

You can find the code here.

Update: 2013/07/27 if you check the gist above you'll see it's been updated so that now a mix a unnamed and named parameters is supported. Named parameters (the NamedParameters object) must be supplied after unnamed parameters)

No comments:

Post a Comment