Reputation: 773
I've got a piece of code from a library which has the following. What is the purpose of options = options || {}
?
var x = function(options) {
options = options || {};
if ('select_message' in options)
options.selectMessage = options.select_message;
// something else
}
At first glance, it seems that options will become either true or false since it uses a boolean operator. But that doesn't really make sense. My hypothesis is that it ensures that "options" will not be undefined, i.e. something like below.
if (typeof options != 'undefined')
options = {};
Upvotes: 1
Views: 50
Reputation: 242
The || is a binary operator that will return the first truthy value. If you do Boolean({}) => true. If options is undefined, {} is return and options is set to this value.
You're thinking is correct. If options passes in something that is "truthy" (http://www.sitepoint.com/javascript-truthy-falsy/), object is set to itself, or just remains the same object. If it is "falsey", it will be set to an empty object.
Upvotes: 1
Reputation: 14419
If options
is falsy (undefined
, false
, null
, 0
, etc) it is assigned {}
(an anonymous object). It is a common pattern when optional arguments can be provided via an object. By making sure options
is assigned at the very least an anonymous object, it makes later code not have to check if it is defined or not when accessing properties on options (like options.something
).
MDN: Falsy
Upvotes: 3