Vince
Vince

Reputation: 1851

Boolean || optimization - "incorrect" values when applied to false vs undefined

I'm just trying to optimize some code (From a beginners stand point).

I have options passed into a function and I want to determine whether a variable is defined in the options object and set it ... or set it to true by default.

I could use jquery to $.extend a default options object but the options object is also used by something else in which I'm only sending certain object properties.

How can this be optimized even shorter (barring white-space):

var show = typeof options.show == 'boolean' ? options.show : true;

This code is definitely quite short but I'm just looking for anything that may be even more compact.

So, using something like:

var show = options.show || true;

doesn't give me proper values.

Example

// Pass in options like { show : false }
var show = options.show || true;
// show will be set to true because options.show === false
// therefore evaluating to the other side of the "||"

Using something like:

var show = !!options.show;
// show will be set to false if options.show is undefined but we want true instead

Abstraction seems to be the only course of action here.

Thanks!

Upvotes: 0

Views: 171

Answers (2)

Matjaž Drolc
Matjaž Drolc

Reputation: 386

You can still use $.extend but with a slight twist to it:

var defaults = {show: true};
var optionsByUser = {};
var defaultsAndUsersOptionsCombined = $.extend({}, defaults, optionsByUser);

As you can see I added {} as the first argument to $.extend. This will make sure that the data is copied to new object instead of modifying defaults or optionsByUser.

Upvotes: 0

histocrat
histocrat

Reputation: 2381

A terse way would be

var show = options.show != false

Since undefined is not equal to false, this sets show to true unless it's set to false.

My preferred way of handling this situation is actually to change the key from "show" to "hide". Then you can safely do

var hide = options.hide

since undefined will behave the same as false when used as a conditional.

Upvotes: 1

Related Questions