How to set default boolean values in JavaScript?
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!
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.)
How about:
this.hasWheels = (typeof hasWheels !== 'undefined') ? hasWheels : true;
Your other option is:
this.hasWheels = arguments.length > 0 ? hasWheels : true;