How to set default boolean values in JavaScript?
How about:
this.hasWheels = (typeof hasWheels !== 'undefined') ? hasWheels : true;
Your other option is:
this.hasWheels = arguments.length > 0 ? hasWheels : true;
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 fromvalue0
for string 'false' if one needs it to be boolean false. I found this relaxation useful occationally.value2
andvalue3
are modifications of original posted answers for consistency, without changed results.value4
is how Babel compiles for default parameters.
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.)