Tuesday, November 13, 2012 Eric Richards

Javascript Needs Default Parameters

Lately, I've been doing a lot of web applications, with C# on the server and ASP MVC/Razor/Javascript clients.  Javascript, especially with jQuery, is really wonderful for manipulating html, but there are a number of things that I've discovered that are unpleasant.  One of the most irritating to me, thus far, is the lack of syntactic sugar for defining default values for  parameters passed to functions.  In other languages that don't support default parameter values, you can often get around this through function overloading - by first defining a function with all the possible arguments, then defining functions with a subset of those arguments, and then calling the ur-function with the missing arguments substituted with default values.

This example is unnecessary in C#, since the language supports the following:

There are a couple of ways I've found to do this in Javascript, neither of which is particularly appealing:

Now, it may be possible to use the C# style syntax if one uses CoffeeScript or TypeScript; I haven't done enough research to know.  But it would be wonderful if javascript supported that syntax natively, just to reduce the amount of boiler-plate that you have to use.  Boilerplate is almost always bad; it introduces the possibility of simple mistakes.