66

Setting default optional values in JavaScript is usually done via the || character

var Car = function(color) {
  this.color = color || 'blue';
};

var myCar = new Car();
console.log(myCar.color); // 'blue'

var myOtherCar = new Car('yellow');
console.log(myOtherCar.color); // 'yellow'

That works because color is undefined and undefined || String is always the String. Of course that also works the other way around String || undefined is String. When two Strings are present the first one wins 'this' || 'that' is 'this'. It does NOT work the other way around as 'that' || 'this' is 'that'.

The question is: How can I achieve the same with boolean values?

Take the following example

var Car = function(hasWheels) {
  this.hasWheels = hasWheels || true;
}

var myCar = new Car();
console.log(myCar.hasWheels); // true

var myOtherCar = new Car(false)
console.log(myOtherCar.hasWheels); // ALSO true !!!!!!

For myCar it works because undefined || true is true but as you can see it does NOT work for myOtherCar because false || true is true. Changing the order doesn't help as true || false is still true.

Therefore, am I missing something here or is the following the only way to set the default value?

this.hasWheels = (hasWheels === false) ? false: true

Cheers!

5 Answers 5

142

You can do this:

this.hasWheels = hasWheels !== false;

That gets you a true value except when hasWheels is explicitly false. (Other falsy values, including null and undefined, will result in true, which I think is what you want.)

Sign up to request clarification or add additional context in comments.

8 Comments

@zeMirco: So you're actually asking for all falsey values except for false to be considered true? If so, I would wonder why you'd want to use || in the first place. Clearly an explicit test for false would be the simplest solution.
@thesystem - He didn't want to use ||; it was just carry-over from using || for non-boolean values. The question was posted, I think, because || was not doing what was needed.
If that's the case, then maybe you can also work it out using ^=.
@minopret - How would you do that?
That's a cool trick, in my case I wanted undefined arguments to be defaulted to false, so I used this.hasWheels = hasWheels === true.
|
6

How about:

this.hasWheels = (typeof hasWheels !== 'undefined') ? hasWheels : true;

Your other option is:

this.hasWheels = arguments.length > 0 ? hasWheels : true;

1 Comment

This does the job well, although I'd suggest using ? !!hasWheels instead of ? hasWheels to guarantee that either true or false (and nothing else) is assigned to this.hasWheels.
5

There are variations to be noted of from posted answers.

var Var = function( value ) {
    this.value0 = value !== false;
    this.value1 = value !== false && value !== 'false';
    this.value2 = arguments.length <= 0 ? true : arguments[0];
    this.value3 = arguments[0] === undefined ? true : arguments[0];
    this.value4 = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0];
};

                     value0   value1   value2        value3         value4
---------------------------------------------------------------------------
Var("")              true     true     true          true           true
Var("''")            true     true     ''            ''             ''
Var("0")             true     true     0             0              0
Var("'0'")           true     true     '0'           '0'            '0'
Var("NaN")           true     true     NaN           NaN            NaN
Var("'NaN'")         true     true     'NaN'         'NaN'          'NaN'
Var("null")          true     true     null          null           null
Var("'null'")        true     true     'null'        'null'         'null'
Var("undefined")     true     true     undefined     true           true
Var("'undefined'")   true     true     'undefined'   'undefined'    'undefined'
Var("true")          true     true     true          true           true
Var("'true'")        true     true     'true'        'true'         'true'
Var("false")         false    false    false         false          false
Var("'false'")       true     false    'false'       'false'        'false'
  • value1 is made especially from value0 for string 'false' if one needs it to be boolean false. I found this relaxation useful occationally.
  • value2 and value3 are modifications of original posted answers for consistency, without changed results.
  • value4 is how Babel compiles for default parameters.

Comments

4

You can use the Default function parameters feature in ECMA6. Today, ECMA6 is still not fully supported in the browser but you can use babel and start using the new features right away.

So, the original example will become as simple as:

// specify default value for the hasWheels parameter
var Car = function(hasWheels = true) {
  this.hasWheels = hasWheels;
}

var myCar = new Car();
console.log(myCar.hasWheels); // true

var myOtherCar = new Car(false)
console.log(myOtherCar.hasWheels); // false

1 Comment

but if someone pass in falsy value (i.e empty string) this.hasWheels will be assigned that empty string instead of a boolean value. probably want to add hasWheels = (typeof hasWheels === 'boolean') ? hasWheels : true;
1

Without much confusion you can do like this to get a default true.

this.hasWheels=typeof hasWheels === 'boolean'?hasWheels:true

To get a default false

this.hasWheels=typeof hasWheels === 'boolean'?false

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.