Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
133
rated 0 times [  137] [ 4]  / answers: 1 / hits: 39773  / 11 Years ago, sun, march 17, 2013, 12:00:00

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!


More From » boolean

 Answers
72

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.)


[#79536] Saturday, March 16, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
elvisissacg

Total Points: 410
Total Questions: 108
Total Answers: 121

Location: Monaco
Member since Tue, Jun 16, 2020
4 Years ago
;