Wednesday 17 July 2013

Javascript Variable Type Checking

Javascript likes many other scripting languages, variable is dynamically typed. That is great during coding but may not be so great when you run into problem during runtime. So what programmer end up doing is to write his own variable type checking code. Generally this is done at the beginning of every function.
function addAB(a,b){
   var a = a || ""; 
   var b = b || "";
   if (!(typeof(a) === number ||
         typeof(b) === number)) return NaN;

   return (a+b);
}

I always feel bored or tired when writing this kind of code. How about you?
Do you guys have some other tricks/ideas to deal with this problem? Why can't scripting language support dynamic typed variable without letting application/us do all these boring work? If you were to change javascript interpreter to understand variable "a" and "b" are numbers and return error if it is anything else, how would it looks like? Here are some ideas:
function addAB(a=>number,b=>number){..}

function addAB(int a, int b){..} // like good old C function

@type a = number
@type b = number
function addAB(a,b){..} // 'notation' in Java/POJO world

var addAB(int, int) = function(a,b){..}

Other ideas? It will be nice if Javascript can elegantly solve or ease this problem.

No comments:

Post a Comment