I often see JavaScript code where a function may take in an “options” object and use it like:
var name = typeof options.name !== 'undefined' ? options.name : "Bob";
This seems like it would be equivalent to the following:
var name = options.name || "Bob";
Now, I understand that in certain situations you may actually care that options.name is undefined vs null and this makes sense to me, but I often see this in situations where this distinction is not necessary.
I believe I have heard that people write code like this because of some bug in IE. Can someone elaborate please?
I am not aware of the bug in IE, but those statements aren’t exactly equivalent:
The first one sets the
namevariable to the default"Bob"only whenoptions.nameisundefined.The second one sets the
namevariable to"Bob"wheneveroptions.nameis falsy. This can be an empty string, thenullvalue, a value of0, theNaNvalue, the boolean valuefalse, and alsoundefined.For example, if
options.name === 0, the first statement will set thenamevariable to0, while the second statement will set it to"Bob".