2010: The Original Blog Post

I've been reading a lotofJavaScriptcode lately, and it's been a joy. I'm picking up on some common JavaScript idioms too, and I thought I'd share.

Introduction to Optional Parameters

Optional parameters are a nice language feature - function parameters that are given default values if not used when calling a function. Optional parameters are great for simplifying code, and hiding advanced but not-often-used functionality. If 90% of the time you're calling a function using the same values for some parameters, you should look into making those parameters optional to avoid Repeating Yourself.

Compare this C# code for connecting to a server, first without optional parameters:

The short-circuit OR operator || returns the left side if the left argument is truthy (evaluates to true in conditionals), otherwise it checks if the right argument is truthy, returning it. We can use this shortcut because undefined is falsy: in conditionals, undefined evaluates to false.

This shortcut approach is a very common idiom, but it does have a disadvantage: You can't use for any argument that could accept a falsy value: false, 0, null, undefined, the empty string "", and NaN.

Using the || shortcut will override any falsy input value. If you expect a falsy value, you must explicitly check for argument === undefined.

This method only allows the last arguments to be optional - you cannot make an optional first parameter, middle parameter, or combination of parameters optional. The next methods let you position optional arguments anywhere.

Method 2: The arguments variable

All JavaScript functions get passed an implicit arguments variable when they're called. arguments is an array containing the values of all the arguments passed to the function. Here's a function that takes any arguments and alert()'s them:

Note that you need to ensure that an object is passed into options, replace it with an empty object {}, or you will get errors trying to read properties from undefined.

A combination of all three methods

Here's an example, from Node.JS's process.watchFile(filename, options, listener) function. It's used to watch filename for changes, calling listener when it does. In this function, the options argument is optional: