options = options || false

2015-03-15

So let me try to clarify this, apparently, highly controversial and opinionated notion that I blurted into the world. Oh sorry about that, world. Frankly the whole thing was more about people seeming to forget you can approach false as you could regular objects, than the way defaulting an options parameter. But hey, it makes for fun twitter discussions, eh?

You're bound to see this kind of JS code, options = options || {}, in a situation where a function takes a bunch of arguments and tries to prevent a monster function header of optional arguments. Alternatively, they may be actual options being passed on to your app or at least to a function that's configurable, or whatever.

Now this case obviously does not apply if you need to augment the options argument with additional data. Such as creating a wrapper that sets up some defaults or specific data for your needs. In that case you obviously still need to create an object regardless.

This case is more about doing the assignment to prevent errors down the line when you inspect options to apply your various options. I don't care about options && (options = {}), which should actually be if (!options) options = {} if you want to go down that path anyways. For some reason I often see the options = options || {} variant more often so I went with it.

Okay so why do options = options || false instead? I can think of three reasons;

One: you can still inspect whether options was passed on in the first place. Sure there are other ways around this, but assigning false doesn't have any of their inevitable drawbacks. You probably don't care about this case though ;)

Two: I think it's more semantically fitting. Let's face it: the only reason we're doing this in the first place, at this point, is to prevent an error down the line. Why would we create a new object for it if we just want another way of saying "null"?

Three: Don't create an object if you don't need to. But let's immediately concede that this is the weakest argument of them all since doing arbitrary property access on primitives may trip up optimizers, it may return false positives if your options clash with built in properties, and this way we nullify the whole perf debate before it even starts. Yup yup *you never saw this paragraph* ...

I hope you notice that this is more a philosophical thing than anything else. I don't care which way you deal with this options thing. They're all good as long as they're working. Unless perf is important (and odds are, this level of perf is not relevant for your case...) you should aim for clear and semantically sound code.

In that light this is actually bad advice because rookie JS coders may be tempted to trip up on doing property access on a falsy value. So maybe assigning a fresh object is the best way to go.

Such maybe. Much wow.